繁体   English   中英

使用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声明为数组,以获取二维数组,然后将其追加。

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

?> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM