2012-09-11 73 views
0

所以我有一個問題,採取一個數組和循環的值和foreach語句輸出。printf問題與陣列

代碼

<?php 
$example = array("test" => "hello world"); 

foreach ($example as $arr) { 
    printf("<p>what do you have to say for yourself?</p><p>%s!</p>",$arr["test"]); 
} 

?> 

希望得到的輸出:

你有什麼話好說?

hello world!

反而得到

你有什麼話好說?

h!

爲什麼只是單個字符?

任何幫助將是巨大的

感謝

回答

4

你的foreach循環通過數組的值已經走,所以不要再次使用關鍵的參考值:

<?php 
$example = array("test" => "hello world"); 

foreach ($example as $key => $val) { 
    printf("<p>what do you have to say for yourself?</p><p>%s!</p>",$val); 
} 

?> 

從評論中的另一個示例中,您將無法使用循環,因爲展示位置非常具體。代替參考每個值特別是沒有環:

$example = array(
    "first" => "Bob", 
    "last" => "Smith", 
    "address" => "123 Spruce st" 
); 
printf("<p>my name is %s %s and i live at %s</p>", 
    $example['first'], 
    $example['last'], 
    $example['address'] 
); 
+1

只要標記正確即可。 – wesside

+0

真棒,但如果我有多個鍵=>值在數組中? – danferth

+0

@danferth:foreach將遍歷數組中的每個鍵/值對,併爲每個鍵運行printf。 –

0

循環您的關聯數組中$arr每次迭代是把一個值。當你嘗試索引到$ arr時,你實際上索引了一個字符串,因此是單個字符。

0

Foreach假定數組中有多個元素。如果不只是echo echo echo $ example ['test'];不需要循環構造。如果一個以上的元素:

$example = array('text'=>"what do you have to say for yourself?",'test' => "hello world"); 

print_r($example); 

foreach ($example as $value) 
printf("<p>%s!</p>",$value); 

的foreach被分配一個數組元素的,在每個循環的變量名爲$的值的值。合理?

1

也許用這種方式來看看會有所幫助;一旦你看到它是如何迭代的,你可以把你的語句放回到printf()中,或者對變量做任何事情。

請注意,如果您有多維數組,你可以通過解決關鍵引用數組的一個新的水平;