这可以完成工作:
$items = array(
(object) array('id' => 42, 'sub_id' => 1),
(object) array('id' => 43, 'sub_id' => 42),
(object) array('id' => 1, 'sub_id' => 0),
);
$childs = array();
foreach($items as $item)
$childs[$item->sub_id][] = $item;
foreach($items as $item) if (isset($childs[$item->id]))
$item->childs = $childs[$item->id];
$tree = $childs[0];
print_r($tree);
这通过首先按 parent_id 索引类别来工作。然后对于每个类别,我们只需将 category->childs 设置为 childs[category->id],然后树就构建好了!
所以,现在 $tree 是类别树。它包含一个 sub_id=0 的项目数组,这些项目本身包含一个他们的孩子的数组,他们自己...
print_r($tree) 的输出:
stdClass Object
(
[id] => 1
[sub_id] => 0
[childs] => Array
(
[0] => stdClass Object
(
[id] => 42
[sub_id] => 1
[childs] => Array
(
[0] => stdClass Object
(
[id] => 43
[sub_id] => 42
)
)
)
)
)
所以这是最终的功能:
function buildTree($items) {
$childs = array();
foreach($items as $item)
$childs[$item->sub_id][] = $item;
foreach($items as $item) if (isset($childs[$item->id]))
$item->childs = $childs[$item->id];
return $childs[0];
}
$tree = buildTree($items);