$source数组在使用树生成函数之前应该特别排序。
尝试使用以下代码在多维数组中创建树
$source = array(
(array('id'=>406,'parent'=>0,'title'=>'level_0_406')),
(array('id'=>270,'parent'=>268,'title'=>'level_0_406_268_270')),
(array('id'=>271,'parent'=>268,'title'=>'level_0_406_268_271')),
(array('id'=>272,'parent'=>268,'title'=>'level_0_406_268_272')),
(array('id'=>273,'parent'=>268,'title'=>'level_0_406_268_273)')),
(array('id'=>269,'parent'=>268,'title'=>'level_0_406_268_269')),
(array('id'=>268,'parent'=>406,'title'=>'level_0_406_268')),
(array('id'=>407,'parent'=>406,'title'=>'level_0_406_407')),
(array('id'=>274,'parent'=>406,'title'=>'level_0_406_274')),
(array('id'=>500,'parent'=>407,'title'=>'level_0_406_407_500')),
);
$result = array();
$links = array(0=>&$result);
foreach ($source as &$element){
$links[$element['id']] = &$element;
$links[$element['parent']]['childs'][$element['id']] = &$element;
}
但结果数组不包含源数组的多个节点,即id=269,270,271,272,273的节点。
Array
(
[childs] => Array
(
[406] => Array
(
[id] => 406
[parent] => 0
[title] => level_0_406
[childs] => Array
(
[268] => Array
(
[id] => 268
[parent] => 406
[title] => level_0_406_268
)
[407] => Array
(
[id] => 407
[parent] => 406
[title] => level_0_406_407
[childs] => Array
(
[500] => Array
(
[id] => 500
[parent] => 407
[title] => level_0_406_407_500
)
)
)
[274] => Array
(
[id] => 274
[parent] => 406
[title] => level_0_406_274
)
)
)
)
)
我尝试了不同的生成树的代码示例,但他们都有相同的问题与源数组,如$source。请帮我理解这种行为。
现在我明白什么是错误的数组。但是,如果我有这样的数据在DB,如何做出正确的选择?
原始$source
数组值未正确创建。应该是:-
$source = array(
(array('id'=>406,'parent'=>0,'title'=>'level_0_406')),
(array('id'=>268,'parent'=>406,'title'=>'level_0_406_268')),
(array('id'=>407,'parent'=>406,'title'=>'level_0_406_407')),
(array('id'=>274,'parent'=>406,'title'=>'level_0_406_274')),
(array('id'=>270,'parent'=>268,'title'=>'level_0_406_268_270')),
(array('id'=>271,'parent'=>268,'title'=>'level_0_406_268_271')),
(array('id'=>272,'parent'=>268,'title'=>'level_0_406_268_272')),
(array('id'=>273,'parent'=>268,'title'=>'level_0_406_268_273)')),
(array('id'=>269,'parent'=>268,'title'=>'level_0_406_268_269')),
(array('id'=>500,'parent'=>407,'title'=>'level_0_406_407_500')),
);
如果您仔细观察,您将看到前面只有父元素ID 407
的子元素是可用的,因为元素ID 407
在子元素出现之前已经定义了。
实际上,您的编码逻辑是首先定义父元素,然后定义子元素。还有一般做法&标准一直都是一样的。
在我的答案中,我已经正确地改变了元素的出现。这应该可以工作。
希望能有所帮助。