如何在php中输出数组?

时间:2011-02-23 05:09:49

标签: php arrays

Array
(
   [menu-162] => Array
    (
        [attributes] => Array
            (
                [title] => example1
            )

        [href] => node/13
        [title] => test1
    )

[menu-219] => Array
    (
        [attributes] => Array
            (
                [title] => example2
            )

        [href] => node/30
        [title] => test2
    )

)

如果我将上面的数组分配给名为$hello的变量,现在,我想使用一个循环只输出menu-162menu-219

如果我只想输出属性标题值,如果我只想输出href的值。

如何编写这些循环?

3 个答案:

答案 0 :(得分:4)

foreach ($hello as $item) {
  $attr = $item['attributes']['title'];
  $href = $item['href'];
  echo "attr is {$attr}";
  echo "href is {$href}";
}

那应输出attr和href。

答案 1 :(得分:0)

您可以访问属性数组中的标题值,如下所示:$hello['menu-162']['attributes']['title'],对于任何其他“菜单”,您可以使用相应的菜单编号组合替换menu-162。至于href一个简单的$hello['menu-162']['href']

至于访问这两个值的循环,一个简单的foreach就足够了:

foreach($hello as $value) {
    echo $value['attributes']['title'];
    echo $value['href'];
}

答案 2 :(得分:0)

foreach($hello as $key => $value) {
    switch($key) {
        case 'menu-162':
        case 'menu-219':
            if($value['href'] && $value['attribute'] && $value['attribute']['title']) {
                $href = $value['href'];
                $attr = $value['attribute']['title'];
            }
        break;
        default:
            continue; //didn't find it
        break;
    }
}

如果您不需要特定的菜单查找,请删除switch语句。如果确实需要使用特定ID,则可以使用更具伸缩性的解决方案,并且比嵌套if更快。它也不会为不存在的变量创建通知,只有在属性title和href都存在的情况下才会返回。