使用foreach语句循环遍历数组


looping through arrays with foreach statement

我有一个数组列表,需要它们与printf语句一起输出

<?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 输出一个字符

试试这样的东西:

// 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']);
}

你可以从这个演示中看到它打印:

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

您还需要将示例声明为一个数组,以获得一个二维数组,然后附加到它。

$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" );

您正在覆盖两行的$example。你需要一个多维的"数组:"

$examples = array();
$examples[] = array("first" ...
$examples[] = array("first" ...
foreach ($examples as $example) {
   foreach ($example as $key => $value) { ...

当然,您也可以立即执行printf,而不是分配数组。

您必须制作一个数组数组,并循环通过主数组:

<?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']);
}
?>