数据表结构:
函数:
function tree($arr, $pid = 0, $level = 1){
static $arr2 = [];
foreach($arr as $v){
if($v['parent_id'] == $pid){
$v['level'] = $level;
$arr2[] = $v;
tree($arr, $v['cat_id'], $level+1);
}
}
return $arr2;
}
tree($list);
结果:
array(19) { [0] => array(6) { ["cat_id"] => string(1) "1" ["cat_name"] => string(6) "女装" ["parent_id"] => string(1) "0" ["sort_order"] => string(2) "50" ["is_show"] => string(1) "1" ["level"] => int(1) } [1] => array(6) { ["cat_id"] => string(1) "6" ["cat_name"] => string(9) "连衣裙" ["parent_id"] => string(1) "1" ["sort_order"] => string(2) "50" ["is_show"] => string(1) "1" ["level"] => int(2) } [2] => array(6) { ["cat_id"] => string(2) "31" ["cat_name"] => string(12) "我的最爱" ["parent_id"] => string(1) "6" ["sort_order"] => string(2) "50" ["is_show"] => string(1) "1" ["level"] => int(3) }
....