【发布时间】:2013-08-08 21:19:47
【问题描述】:
我要疯了,我不明白这是什么问题。
我有这个数组:
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;
}
【问题讨论】:
-
在
$result.= '<li>Cat: ' . $node['name'];行之前使用var_dump或print_r。它会告诉你 $node 的内容,你将能够看到它在哪里/为什么抛出 NOTICE(不是错误)。 -
你能指出你得到未定义索引错误的代码行吗?
-
如果我使用 var_dump 我得到未定义的索引 Notica,但 laravel 允许我做 dd(); $node 的内容是: array(4) { ["id"]=> string(1) "1" ["parent_id"]=> NULL ["name"]=> string(7) "事件" ["children"]=> array(2) { [0]=> array(3) { ["id"]=> string(1) "2" ["parent_id"]=> string(1) " 1" ["name"]=> string(9) "演唱会" } [1]=> array(3) { ["id"]=> string(1) "3" ["parent_id"]=> string( 1) "1" ["name"]=> string(10) "Parties" } } } and of $nodo['name'] string(7) "Events"
-
通知行是:$result .= '
- Cat: '.$nodo['name'];
标签: php arrays recursion laravel undefined