PHP foreach 循环遍历多维数组[重复]

问题描述 投票:0回答:4

我有一个数组:

$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
4个回答
41
投票
$last = count($arr_nav) - 1;

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

    echo ... $row['name'] ... $row['url'] ...;
}

5
投票
<?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
)

2
投票

如果您在谈论 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 可能会更好..


0
投票
<?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 生成器中回显该类。可能需要某种检查来确保类已设置,或者为数组提供默认的空类。

© www.soinside.com 2019 - 2024. All rights reserved.