我要疯了,我不明白问题出在哪里。
我有这个阵列:
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;
}
我得到一个"未定义的索引:名称"错误。我需要申报姓名吗?怎样数组是否语法不正确?
如果我评论递归调用
$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;
}
您正在将$node['children']
推送到一个额外的数组中。这样,您就不会处理这个节点的子数组(稍后会有一个名称),而是有另一层数组。
跳过此阵列层,将其移除。
还要注意,如果您想将该变量用作数组,那么!is_null()
并不是一个很好的检查。请检查is_array()
,因为字符串和其他标量值也将返回count>0
——它们返回1。只有NULL返回count=0。
您必须将子节点的printTree()连续调用返回的结果附加到$result中。
$result .= $this->printTree($node['children']);
:)
首先,您希望将$subtree内容封装到if条件中,以检查键"children"的存在,因为现在,您已经创建了对printTree()
的递归调用的无限循环,但您只想在键"children'"存在的情况下执行此操作。
其次,我猜您希望在$this->printTree($subtree);
前面添加$result .=
,否则返回值将被丢弃。
第三,不要做$subtree = array($node['children']);
。$node['children']
已经是一个数组,所以这为数组添加了另一个级别,这使得递归中断。
所以,最后的函数应该是这样的:
public function printTree($tree) {
$result = '';
if(!is_null($tree) && count($tree) > 0) {
$result .= '<ul>';
foreach($tree as $node) {
$result .= '<li>Cat: '.$node['name'];
if (isset($node['children'])) {
$subtree = $node['children'];
$result .= $this->printTree($subtree);
}
$result .= '</li>';
}
$result .= '</ul>';
}
return $result;
}
编辑:哇,那里太慢了,其他人也在这里发现了三个问题:)