扫码关注官方订阅号
除了使用递归的方式实现之外还有什么方式可以实现无限级呢??
光阴似箭催人老,日月如移越少年。
$categories = [ ['id'=>1,'cat_id'=>1,'cat_name'=>'a','pid'=>0], ['id'=>2,'cat_id'=>2,'cat_name'=>'b','pid'=>1], ['id'=>3,'cat_id'=>3,'cat_name'=>'c','pid'=>1], ['id'=>4,'cat_id'=>4,'cat_name'=>'d','pid'=>2], ['id'=>5,'cat_id'=>5,'cat_name'=>'e','pid'=>3], ]; $tree = []; foreach($categories as $v){ $tree[$v['id']] = $v; $tree[$v['id']]['children'] = array(); } foreach ($tree as $k=>$v) { if ($v['pid'] > 0) { $tree[$v['pid']]['children'][] = &$tree[$k]; } } print_r($tree);
可以 自连接递归
自连接递归
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 ( ) ) ) ) ) ) )
可以迭代循环
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
可以
自连接递归使用递归
使用PHP的指针特性
使用
传入你的上述数组,比如最顶层的ID为0
结果
可以迭代循环