这是我的数组: $list = array( array('id' => 3, 'name' => 'Phones', 'parent_id' => 0,), array('id' => 256, 'name' => 'Accessories', 'parent_id' => 0,), array('id' => 308, 'name' => 'Appliances', 'parent_id' => 0,), array('id' => 1057, 'name' => 'Smart', 'parent_id' => 0,), array('id' => 1065, 'name' => 'Smart Phones', 'parent_id' => 3,), array('id' => 1066, 'name' => 'Feature Phones', 'parent_id' => 3,), array('id' => 1069, 'name' => 'Samsung', 'parent_id' => 1065,), array('id' => 1070, 'name' => 'Apple', 'parent_id' => 1065,), array('id' => 1072, 'name' => 'Apple', 'parent_id' => 1066,), array('id' => 1075, 'name' => 'Tablets', 'parent_id' => 0,), array('id' => 1076, 'name' => 'Samsung', 'parent_id' => 1066,), array('id' => 1077, 'name' => 'All Brands', 'parent_id' => 1075,), array('id' => 1078, 'name' => 'Samsung', 'parent_id' => 1077,), array('id' => 1079, 'name' => 'Protector', 'parent_id' => 256,), array('id' => 1080, 'name' => 'Power', 'parent_id' => 256,), array('id' => 1081, 'name' => 'Cable', 'parent_id' => 256,), array('id' => 1082, 'name' => 'Memory', 'parent_id' => 256,), );这是我分类的代码:function quote_make_tree($list,$deep=1, $root = 0){ $tree = $packData = []; foreach ($list as $row) { $packData[$row['id']] = $row; } foreach ($packData as $key => $val) { if ($val['parent_id'] == $root) { $tree[] = &$packData[$key]; } else { $packData[$val['parent_id']]['children'][] = &$packData[$key]; } } return $tree;}我想添加一个深度参数$deep来quote_make_tree控制分类的深度。if $deep = 2,获取level 1分类下的level 2分类,if $deep=3,获取所有1,2,3分类我已经尝试先获取所有数据,然后根据$deep.here is demo删除数据,谢谢大家
1 回答
守候你守候我
TA贡献1802条经验 获得超10个赞
使用递归方法可能更容易解决。这使您可以检查深度,如果您想要更多细节,那么它将调用自己添加更多层。每次称自己时,您只需从深度中删除一个...
function quote_make_tree($list, $deep=1, $root = 0) {
$output = [];
foreach ( $list as $listItem ) {
if ( $listItem['parent_id'] == $root ) {
if ( $deep > 1 ) {
$listItem['children'] = quote_make_tree($list, $deep-1, $listItem['id']);
}
$output[] = $listItem;
}
}
return $output;
}
- 1 回答
- 0 关注
- 120 浏览
添加回答
举报
0/150
提交
取消