Home >Backend Development >PHP Tutorial >请问这段代码到底什么问题? 为什么会报错;

请问这段代码到底什么问题? 为什么会报错;

WBOY
WBOYOriginal
2016-06-23 13:35:151294browse

Array(    [0] => Array        (            [id] => 3            [fid] => 0            [name] => 333            [son] => Array                (                    [0] => Array                        (                            [id] => 2                            [fid] => 3                            [name] => 2_3                            [son] => Array                                (                                    [0] => Array                                        (                                            [id] => 4                                            [fid] => 2                                            [name] => 2_4                                        )                                )                        )                    [1] => Array                        (                            [id] => 5                            [fid] => 3                            [name] => 2_3                        )                )        )    [1] => Array        (            [id] => 1            [fid] => 0            [name] => 111        ))

这是一个tree结构的数组,我希望在每个数组元素上加一个层级元素;
function tree_add_level($tree){    foreach($tree as &$val){    	if(!isset($val['_level'])){    	    $val['_level']=0;//顶层为0    	}		if(isset($val['son'])){            $val['son']['_level']=$val['_level']+1; //下级加1            tree_add_level($val['son']);        }    }    return $tree;}


但是却提示语法错误,求解决方法,或者其他方式. 谢谢


回复讨论(解决方案)

提示: Warning: Cannot use a scalar value as an array in D:\Web\BOOT\newfile.php on line 28
 tree_add_level($val['son']); 这句代码到底有什么问题? 递归下而已.

你需要判断一下$tree是否是数组

你需要判断一下$tree是否是数组



$tree 和 $tree['son']  100%是数组;  测试的就是上面的案例数组;

你这个数组能粘贴出来吗,我测试一下

你需要判断一下$tree是否是数组



谢谢,我加的

你这个数组能粘贴出来吗,我测试一下



谢谢了,已经解决了; 是逻辑错误,少了层引用;
function tree_add_level(&$tree,$n=0){
    foreach($tree as &$val){
     $val['_level']=$n;
isset($val['son']) && tree_add_level($val['son'],$n+1);
    }
}

警告其实不影响,只要你得到了你想要的结果

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn