【问题标题】:PHP foreach loop through multidimensional array [duplicate]PHP foreach循环遍历多维数组
【发布时间】:2010-10-24 23:38:03
【问题描述】:

我有一个数组:

$arr_nav = array( array( "id" => "apple", 
          "url" => "apple.html",
          "name" => "My Apple" 
        ),
        array( "id" => "orange", 
          "url" => "orange/oranges.html",
          "name" => "View All Oranges",
        ),
        array( "id" => "pear", 
          "url" => "pear.html",
          "name" => "A Pear"
        )       
 );

我想使用 foreach 循环来替换(它只允许我设置数字:

for ($row = 0; $row < 5; $row++)

能够为相关数组值显示 .first.last

编辑

我希望将数据回显为:

<li id="' . $arr_nav[$row]["id"] . '"><a href="' . $v_url_root . $arr_nav[$row]["url"] . '" title="' . $arr_nav[$row]["name"] . '">"' . $arr_nav[$row]["name"] . '</a></li>' . "\r\n";

非常感谢您的快速回复。 StackOverflow 摇滚!

【问题讨论】:

    标签: php arrays loops multidimensional-array


    【解决方案1】:
    $last = count($arr_nav) - 1;
    
    foreach ($arr_nav as $i => $row)
    {
        $isFirst = ($i == 0);
        $isLast = ($i == $last);
    
        echo ... $row['name'] ... $row['url'] ...;
    }
    

    【讨论】:

    • 非常感谢!我使用: (($isLast) ? ' class="last-child"' : '') 将一个类添加到列表项
    【解决方案2】:
    <?php
    $php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTI", "p_type"=>"ARRAY"));
    
    //Iterate through an array declared above
    
    foreach($php_multi_array as $key => $value)
    {
        if (!is_array($value))
        {
            echo $key ." => ". $value ."\r\n" ;
        }
        else
        {
           echo $key ." => array( \r\n";
    
           foreach ($value as $key2 => $value2)
           {
               echo "\t". $key2 ." => ". $value2 ."\r\n";
           }
    
           echo ")";
        }
    }
    ?>
    

    输出:

    lang => PHP
    type => array( 
        c_type => MULTI
        p_type => ARRAY
    )
    

    Reference Source Code

    【讨论】:

    【解决方案3】:
    <?php
    $first = reset($arr_nav); // Get the first element
    $last  = end($arr_nav);   // Get the last element
    // Ensure that we have a first element and that it's an array
    if(is_array($first)) { 
       $first['class'] = 'first';
    }
    // Ensure we have a last element and that it differs from the first
    if(is_array($last) && $last !== $first) {
       $last['class'] = 'last';
    }
    

    现在您可以在 html-generator 中回显类。可能需要进行某种检查以确保已设置类,或为数组提供默认的空类。

    【讨论】:

      【解决方案4】:

      如果你在谈论 a.first 和 a.last 时指的是数组的第一个和最后一个条目,它是这样的:

      foreach ($arr_nav as $inner_array) {
          echo reset($inner_array); //apple, orange, pear
          echo end($inner_array); //My Apple, View All Oranges, A Pear
      }
      

      PHP 中的数组有一个内部指针,您可以使用 resetnextend 来操作它。检索键/值适用于 keycurrent,但在许多情况下使用 each 可能会更好..

      【讨论】:

    • 这应该是公认的答案。很多创意。!!
    • 猜你喜欢
      相关资源
      最近更新 更多
      热门标签