PHP foreach循环遍历多维数组

时间:2009-05-09 08:33:30

标签: php arrays loops multidimensional-array

我有一个数组:

$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摇滚!

4 个答案:

答案 0 :(得分:35)

$last = count($arr_nav) - 1;

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

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

答案 1 :(得分: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
)

<强> Reference Source Code

答案 2 :(得分: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可能会更好..

答案 3 :(得分: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-generator中回应这个类。可能需要进行某种检查以确保设置类,或者为数组提供默认的空类。