2009-07-21 20 views
5
$posts = array(
"message" => 'this is a test message' 
); 

foreach ($posts as $post) { 
    echo $post['message']; 
} 

Perché il codice sopra riportato emette solo la prima lettera nel messaggio? "T".Array e foreach

Grazie!

+0

Sono davvero sorpreso di stampare qualcosa ... Non dovresti essere in grado di indicizzare in una stringa utilizzando un parametro associativo (es. una stringa) ... Direi che questo è probabilmente un comportamento indefinito al meglio. –

+1

@ Matthew: la spiegazione è nella mia risposta. – soulmerge

risposta

12

foreach prende ogni elemento della matrice e lo assegna alla variabile. Per ottenere i risultati presumo vi aspettate basta fare:

foreach ($posts as $post) { 
    echo $post; 
} 

Le specifiche per quanto riguarda il motivo per cui il codice non ha funzionato: $post sarebbe il contenuto del elemento dell'array - in questo caso una stringa. Perché PHP non è fortemente tipizzato/supporta tipo giocoleria, è possibile nel lavoro fatto con una stringa come se fosse un array, e arrivare a ogni carattere nella sequenza:

foreach ($posts as $post) { 
    echo $post[0]; //'t' 
    echo $post[1]; //'h' 
} 

Ovviamente $post['message'], pertanto, non è una valida elemento, e non vi è alcuna conversione esplicita da (string)'message' a int, quindi questo valore corrisponde a $post[0].

+1

((int) 'message') è abbastanza ben definito: http://de.php.net/manual/en/language.types.string.php#language.types.string.conversion – soulmerge

+0

Molto vero: cattiva scelta di vocabolario da parte mia per esprimere ciò che intendevo – Ian

6
# $posts is an array with one index ('message') 
$posts = array(
    "message" => 'this is a test message' 
); 

# You iterate over the $posts array, so $post contains 
# the string 'this is a test message' 
foreach ($posts as $post) { 
    # You try to access an index in the string. 
    # Background info #1: 
    # You can access each character in a string using brackets, just 
    # like with arrays, so $post[0] === 't', $post[1] === 'e', etc. 
    # Background info #2: 
    # You need a numeric index when accessing the characters of a string. 
    # Background info #3: 
    # If PHP expects an integer, but finds a string, it tries to convert 
    # it. Unfortunately, string conversion in PHP is very strange. 
    # A string that does not start with a number is converted to 0, i.e. 
    # ((int) '23 monkeys') === 23, ((int) 'asd') === 0, 
    # ((int) 'strike force 1') === 0 
    # This means, you are accessing the character at position ((int) 'message'), 
    # which is the first character in the string 
    echo $post['message']; 
} 

Quello che forse desidera o è questo:

$posts = array(
    array(
     "message" => 'this is a test message' 
    ) 
); 
foreach ($posts as $post) { 
    echo $post['message']; 
} 

O questo:

$posts = array(
    "message" => 'this is a test message' 
); 
foreach ($posts as $key => $post) { 
    # $key === 'message' 
    echo $post; 
} 
+0

+1 per informazioni di sfondo veramente belle (: – peirix

+0

Questo non risolve veramente il problema, che è un'errata concezione errata su come funziona foreach con gli array. – Ian

+0

"Risolvere il problema"? Non riesco a risolvere il problema senza sapere cosa vuole ottenere con la sua sceneggiatura, posso solo rispondere alla sua domanda e dare esempi di lavoro, ma penso che le informazioni qui siano sufficienti per far funzionare la sceneggiatura. – soulmerge

4

mi piacerebbe aggiungere al di Ian risposta qualcosa: se si vuole in qualche modo per accedere alla chiave del valore, utilizzare:

foreach ($posts as $key => $post) { 
    echo $key . '=' . $post; 
} 

Risultato:

message=this is a test message