我得到了Undefined索引:递归地读取一个数组

时间:2013-08-08 21:19:48

标签: php arrays recursion laravel undefined

我会变得疯狂,我无法理解这是什么问题。

我有这个数组:

array(2) {
      [0]=>
      array(4) {
        ["id"]=>
        string(1) "1"
        ["parent_id"]=>
        NULL
        ["name"]=>
        string(7) "Events"
        ["children"]=>
        array(2) {
          [0]=>
          array(3) {
            ["id"]=>
            string(1) "2"
            ["parent_id"]=>
            string(1) "1"
            ["name"]=>
            string(9) "Concerts"
          }
        }
      }
      [1]=>
      array(4) {
        ["id"]=>
        string(1) "4"
        ["parent_id"]=>
        NULL
        ["name"]=>
        string(7) "Music"
        ["children"]=>
        array(3) {
          [0]=>
          array(3) {
            ["id"]=>
            string(1) "5"
            ["parent_id"]=>
            string(1) "4"
            ["name"]=>
            string(4) "Rock"
          }
        }
      }
    }

我试着用这个递归函数打印:

public function printTree($tree) {
    $result = "";
    if(!is_null($tree) && count($tree) > 0) {
        $result .= '<ul>';
        foreach($tree as $node) {
            $result .= '<li>Cat: '.$node['name'];
                $subtree = array($node['children']);
                $this->printTree($subtree);
            $result .= '</li>';
        }
        $result .= '</ul>';
    }
    return $result;
}

我收到“Undefined index:name”错误。 我需要申报姓名吗?怎么样? 数组的语法是否正确?

如果我评论递归调用

$subtree = array($node['children']);
$this->printTree($subtree);, 

然后$node['name']未定义且代码有效,但当然只有一个深度。

解决:(谢谢所有人!)

public function printTree($tree) {
    $result = "";
    if(is_array($tree) && count($tree) > 0) {
        $result .= '<ul>';
        foreach($tree as $node) {
            $result .= '<li>Cat: '.$node['name'];
                if (isset($node['children'])) { 
                    $result .= $this->printTree($node['children']);
                }
            $result .= '</li>';
        }
        $result .= '</ul>';
    }
    return $result;
}

3 个答案:

答案 0 :(得分:1)

您正在将$node['children']推送到其他阵列中。这样你就不会处理这个节点的子阵列(稍后会有一个名字),但你有另一层数组。

跳过此数组图层,将其删除。

另请注意,如果您希望将该变量用作数组,那么!is_null()并不是一个很好的检查。请检查is_array(),因为字符串和其他标量值也会返回count>0 - 它们返回1.只有NULL返回count = 0.

答案 1 :(得分:1)

您必须将对子节点的printTree()连续调用返回的结果附加到$ result。

$result .= $this->printTree($node['children']);

:)

答案 2 :(得分:1)

首先,您希望将$ subtree-stuff包含在if条件中,检查是否存在关键的'children',因为就像现在一样,您创建了一个无限循环的递归调用{{ 1}},但是如果密钥'children'存在,你只想这样做。

其次,我想你想在printTree()前添加$result .=,否则返回值就会被丢弃。

第三,不要$this->printTree($subtree);$subtree = array($node['children']);已经是一个数组,因此这会为数组添加另一个级别,这会使递归中断。

所以,最终的函数应该是这样的:

$node['children']

编辑:哎呀,在那里太慢了,其他人也在这里发现了三个问题:)