2010-08-15 13 views
21

Ho un POST in PHP per il quale non sempre conosco i nomi dei campi variabili che elaborerò.

Ho una funzione che sarà un ciclo tra i valori (però mi vorrebbe anche per catturare il nome della variabile che va con esso.)

foreach ($_POST as $entry) 
{ 
    print $entry . "<br>"; 
} 

Una volta che ho a capire come per afferrare i nomi delle variabili, ho anche bisogno di capire come posso rendere la funzione abbastanza intelligente da rilevare e passare attraverso gli array per una variabile se sono presenti (cioè se ho alcuni valori di checkbox.)

+2

questa domanda è certamente non localizzato, perché ho passato una situazione simile . – IcyFlame

risposta

41

Se si desidera solo per stampare l'intero array $ _POST per verificare i dati che viene inviato correttamente, utilizzare print_r:

print_r($_POST); 

Per stampare ricorsivamente il contenuto di un array:

printArray($_POST); 

function printArray($array){ 
    foreach ($array as $key => $value){ 
     echo "$key => $value"; 
     if(is_array($value)){ //If $value is an array, print it as well! 
      printArray($value); 
     } 
    } 
} 

Applicare un po DiPAD zione di matrici nidificate:

printArray($_POST); 

/* 
* $pad='' gives $pad a default value, meaning we don't have 
* to pass printArray a value for it if we don't want to if we're 
* happy with the given default value (no padding) 
*/ 
function printArray($array, $pad=''){ 
    foreach ($array as $key => $value){ 
     echo $pad . "$key => $value"; 
     if(is_array($value)){ 
      printArray($value, $pad.' '); 
     } 
    } 
} 

is_array restituisce vero se la variabile data è un array.

È inoltre possibile utilizzare array_keys che restituirà tutti i nomi di stringa.

5

Puoi avere il ciclo foreach mostrare l'indice lungo con il valore:

foreach ($_POST as $key => $entry) 
{ 
    print $key . ": " . $entry . "<br>"; 
} 

Per quanto riguarda la matrice verifica, utilizzare la funzione is_array():

foreach ($_POST as $key => $entry) 
{ 
    if (is_array($entry)) { 
     foreach($entry as $value) { 
      print $key . ": " . $value . "<br>"; 
     } 
    } else { 
     print $key . ": " . $entry . "<br>"; 
    } 
} 
0

Se si desidera rilevare campi matrice utilizzano un codice come questo:

foreach ($_POST as $key => $entry) 
{ 
    if(is_array($entry)){ 
     print $key . ": " . implode(',',$entry) . "<br>"; 
    } 
    else { 
     print $key . ": " . $entry . "<br>"; 
    } 
} 
1

E 'molto meglio usare:

if (${'_'.$_SERVER['REQUEST_METHOD']}) { 
    $kv = array(); 
    foreach (${'_'.$_SERVER['REQUEST_METHOD']} as $key => $value) { 
     $kv[] = "$key=$value"; 
    } 
} 
Problemi correlati