34

我有一个数组:

$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++)

能够显示相关数组值的a.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

4 回答 4

39
$last = count($arr_nav) - 1;

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

    echo ... $row['name'] ... $row['url'] ...;
}
于 2009-05-09T08:54:47.910 回答
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
)

参考源代码

于 2013-04-04T18:44:51.977 回答
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,但在许多情况下使用每个可能会更好..

于 2009-05-09T08:40:51.423 回答
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 中回显类。可能需要某种检查以确保已设置类,或为数组提供默认的空类。

于 2009-05-09T09:10:06.313 回答