【问题标题】:looping through arrays with foreach statement使用 foreach 语句遍历数组
【发布时间】:2013-07-04 04:19:20
【问题描述】:

我有一个数组列表,需要用 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 =&gt; value 组合生成&lt;p&gt;。这只是一个简化的示例,因为输出的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 =&gt; value输出一个字符

【问题讨论】:

  • 您声明了两次$example - 第二次将覆盖第一次。那肯定没用。

标签: php arrays


【解决方案1】:

试试这样的:

// 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

【讨论】:

  • 太棒了,这就是我将 $example 声明为数组时所缺少的!谢谢你。并为演示 +1!
  • 不客气!澄清一下,不需要将其声明为数组,因为 $example[] 将隐式创建 $example 作为数组。但是,在使用变量之前定义变量是我的偏好和一般最佳实践。
【解决方案2】:

您还需要将 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" );

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:

      您必须创建一个数组并循环遍历主数组:

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

      【讨论】:

        猜你喜欢
        • 2014-07-31
        • 1970-01-01
        • 2016-04-06
        • 1970-01-01
        • 2021-01-18
        • 2020-05-19
        • 1970-01-01
        • 2013-12-16
        • 1970-01-01
        相关资源
        最近更新 更多