我要疯了,我不明白这是什么问题。
我有这个数组:
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);,
then$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;
}