0

我有一个数组列表,需要它们用 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组合生成 a 。这只是一个简化的例子,因为真实世界的代码在输出中会更复杂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

4 回答 4

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

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

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
于 2012-09-11T18:46:44.407 回答
1

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

$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" );
于 2012-09-11T18:46:54.147 回答
0

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

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

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

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

于 2012-09-11T18:47:30.437 回答
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']);
}

?> 
于 2012-09-11T18:48:38.870 回答