一尘不染

PHP foreach遍历多维数组

php

我有一个数组:

$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令人震惊!


阅读 430

收藏
2020-05-29

共1个答案

一尘不染

$last = count($arr_nav) - 1;

foreach ($arr_nav as $i => $row)
{
    $isFirst = ($i == 0);
    $isLast = ($i == $last);

    echo ... $row['name'] ... $row['url'] ...;
}
2020-05-29