除了使用递归的方式实现之外还有什么方式可以实现无限级呢??
function _data_to_tree(&$items, $topid = 0, $with_id = TRUE)
{
$result = [];
foreach($items as $v)
if ($topid == $v['parent']) {
$r = $v + ['children' => _data_to_tree($items, $v['id'], $with_id)];
if ($with_id)
$result[$v['id']] = $r;
else
$result[] = $r;
}
return $result;
}
function _data_to_tree($items, $topid = 0, $with_id = TRUE)
{
if ($with_id)
foreach ($items as $item)
$items[ $item['parent'] ]['children'][ $item['id'] ] = &$items[ $item['id'] ];
else
foreach ($items as $item)
$items[ $item['parent'] ]['children'][] = &$items[ $item['id'] ];
return isset($items[ $topid ]['children']) ? $items[ $topid ][ 'children' ] : [];
}
//注意本算法 不会输出 0 的根节点
//并且数据必须有KEY,并且需要与id相等,也就是如下格式:
// 1 => ['id' => 1]
// 2 => ['id' => 2]
传入你的上述数组,比如最顶层的ID为0
$data = [
4 => ['id' => 4, 'parent' => 1 , 'text' => 'Parent1'],
1 => ['id' => 1, 'parent' => 0 , 'text' => 'Root'],
2 => ['id' => 2, 'parent' => 1 , 'text' => 'Parent2'],
3 => ['id' => 3, 'parent' => 2 , 'text' => 'Sub1'],
];
print_r ( _data_to_tree($data, 0) );
Array
(
[1] => Array
(
[id] => 1
[parent] => 0
[text] => Root
[children] => Array
(
[4] => Array
(
[id] => 4
[parent] => 1
[text] => Parent1
[children] => Array
(
)
)
[2] => Array
(
[id] => 2
[parent] => 1
[text] => Parent2
[children] => Array
(
[3] => Array
(
[id] => 3
[parent] => 2
[text] => Sub1
[children] => Array
(
)
)
)
)
)
)
)
2 回答1.5k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
2 回答871 阅读✓ 已解决
1 回答1.1k 阅读✓ 已解决
2 回答930 阅读
1 回答912 阅读
1 回答841 阅读