2012-09-11 90 views
0

我有陣列的列表,並需要他們輸出與printf語句通過與foreach語句陣列

<?php 
$example = array("first" => "Bob", "last" => "Smith", "address" => "123 Spruce st"); 
$example = array("first" => "Sara", "last" => "Blask", "address" => "5678 Maple ct"); 

foreach ($example as $key => $val) { 
    printf("<p>hello my name is %s %s and i live at %s</p>",$example['first'],$example['last'], $example['address']); 
} 

?> 

上面剛剛過去的陣列輸出循環,我就需要遍歷所有的陣列和用提供的key => value組合產生<p>。這僅僅是作爲現實世界中的代碼將在輸出html

更復雜的我試過

foreach ($example as $arr){ 
printf("<p>hello my name is %s %s and i live at %s</p>",$arr['first'],$arr['last'], $arr['address']); 
} 

一個簡單的例子,但它只能輸出每個key => value

+3

你聲明'$ example'兩次 - 第二個將在寫的第一個。這絕對沒有幫助。 – andrewsi

回答

2

單個字符嘗試是這樣的:

// Declare $example as an array, and add arrays to it 
$example = array(); 
$example[] = array("first" => "Bob", "last" => "Smith", "address" => "123 Spruce st"); 
$example[] = array("first" => "Sara", "last" => "Blask", "address" => "5678 Maple ct"); 

// Loop over each sub-array 
foreach($example as $val) { 
    // Access elements via $val 
    printf("<p>hello my name is %s %s and i live at %s</p>",$val['first'],$val['last'], $val['address']); 
} 

您可以從this demo看到它打印:

hello my name is Bob Smith and i live at 123 Spruce st 
hello my name is Sara Blask and i live at 5678 Maple ct 
+0

真棒這就是我失蹤宣佈$例如數組!謝謝。併爲演示+1! – danferth

+0

不客氣!爲了澄清,不需要將其聲明爲數組,因爲'$ example []'會隱式地創建'$ example'作爲數組。但是,在使用它們之前,定義變量是我的首選,也是一種通用的最佳做法。 – nickb

1

您需要將示例聲明爲數組以便獲取2維數組,然後將其附加到它。

$example = array(); 
$example[] = array("first" => "Bob", "last" => "Smith", "address" => "123 Spruce st"); # appends to array $example 
$example[] = array("first" => "Sara", "last" => "Blask", "address" => "5678 Maple ct"); 
0

你覆蓋在兩條線上$example。你需要一個多維「數組的數組:」

$examples = array(); 
$examples[] = array("first" ... 
$examples[] = array("first" ... 

foreach ($examples as $example) { 
    foreach ($example as $key => $value) { ... 

當然,你也可以做printf立即而不是分配陣列。

0

你必須通過主陣列,使您的陣列和循環數組:

<?php 

$examples[] = array("first" => "Bob", "last" => "Smith", "address" => "123 Spruce st"); 
$examples[] = array("first" => "Sara", "last" => "Blask", "address" => "5678 Maple ct"); 

foreach ($examples as $example) { 
    printf("<p>hello my name is %s %s and i live at %s</p>",$example['first'],$example['last'], $example['address']); 
} 

?>