category.php 1, 'name'='关于我们', 'parent_id'=0],['id'=2, 'name'='品牌产品', 'parent_id'=0],['id'=101, 'name'='公司概况', 'parent_id'=1],['id'=102, 'name'='企业文化', 'parent_id'=1],['id'=103, 'name'='品牌介绍', 'parent
1, 'name'=>'关于我们', 'parent_id'=>0], ['id'=>2, 'name'=>'品牌产品', 'parent_id'=>0], ['id'=>101, 'name'=>'公司概况', 'parent_id'=>1], ['id'=>102, 'name'=>'企业文化', 'parent_id'=>1], ['id'=>103, 'name'=>'品牌介绍', 'parent_id'=>2], ['id'=>104, 'name'=>'产品服务', 'parent_id'=>2] ]; /** * * php二级分类遍历 */ function demo($list,$pid=0) { $arr = []; $tree= []; foreach ($list as $value) { $arr[$value['parent_id']][]=$value; } foreach ($arr[$pid] as $key=>$val) { $tree[$key][] = $val; foreach ($arr[$val['id']] as $v) { $tree[$key]['son'][]=$v; } } return $tree; } $list = demo($category); echo ''; print_r($list); /** * * php多级数据遍历 */ function getTree($list, $pid = 0) { $tree = []; if (!empty($list)) { //先修改为以id为下标的列表 $newList = []; foreach ($list as $k => $v) { $newList[$v['id']] = $v; } //然后开始组装成特殊格式 foreach ($newList as $value) { if ($pid == $value['parent_id']) {//先取出顶级 $tree[] = &$newList[$value['id']]; } elseif (isset($newList[$value['parent_id']])) { //再判定非顶级的pid是否存在,如果存在,则再pid所在的数组下面加入一个字段items,来将本身存进去 $newList[$value['parent_id']]['items'][] = &$newList[$value['id']]; } } } return $tree; }