使用foreach语句循环遍历数组

时间:2012-09-11 18:44:00

标签: php arrays

我有一个数组列表,需要输出一个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']);
}

?> 

上面只输出最后一个数组,我需要它遍历所有数组并使用提供的<p>组合产生key => value。这只是一个简化的例子,因为输出的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

输出一个字符

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

你在两行都覆盖了$example。你需要一个多维的阵列数组:&#34;

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

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

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

答案 3 :(得分: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']);
}

?>