$list = [ ["id"=>1,"pid"=>0,"name"=>"书本"], ["id"=>2,"pid"=>0,"name"=>"动画"], ["id"=>3,"pid"=>0,"name"=>"手机"], ["id"=>4,"pid"=>1,"name"=>"名著"], ["id"=>5,"pid"=>1,"name"=>"古籍"], ["id"=>6,"pid"=>4,"name"=>"钢铁是怎么炼成的"], ["id"=>7,"pid"=>4,"name"=>"罗密欧与朱丽叶"], ["id"=>8,"pid"=>5,"name"=>"三字经"], ["id"=>9,"pid"=>2,"name"=>"乐陶陶"], ["id"=>10,"pid"=>2,"name"=>"熊出没"], ["id"=>11,"pid"=>3,"name"=>"华为"], ["id"=>12,"pid"=>3,"name"=>"Vivo"], ];

将list数据进行无限分类,除了上期文章利用的方法,我们还可以利用“引用(&)”的技巧

$tree = [];$temp = [];foreach($list as $key=>$item){ $temp[$item['pid']] = &$list[$key]; $pid = $item['pid']; if($pid==0){ // 判断是否为顶级菜单 $tree[] = &$list[$key]; }else{ if(isset($temp[$pid])){ $temp[$pid]['sub'][] = &$list[$key]; } }}// 返回的列表为 $tree

我们得到的数据构造如下:

php树型Php无穷分类树形构造二 Docker

array:3 [ 0 => & array:4 [ "id" => 1 "pid" => 0 "name" => "书本" "sub" => array:2 [ 0 => & array:4 [ "id" => 4 "pid" => 1 "name" => "名著" "sub" => array:2 [ 0 => & array:3 [ "id" => 6 "pid" => 4 "name" => "钢铁是怎么炼成的" ] 1 => & array:3 [ "id" => 7 "pid" => 4 "name" => "罗密欧与朱丽叶" ] ] ] 1 => & array:4 [ "id" => 5 "pid" => 1 "name" => "古籍" "sub" => array:1 [ 0 => & array:3 [ "id" => 8 "pid" => 5 "name" => "三字经" ] ] ] ] ] 1 => & array:4 [ "id" => 2 "pid" => 0 "name" => "动画" "sub" => array:2 [ 0 => & array:3 [ "id" => 9 "pid" => 2 "name" => "乐陶陶" ] 1 => & array:3 [ "id" => 10 "pid" => 2 "name" => "熊出没" ] ] ] 2 => & array:4 [ "id" => 3 "pid" => 0 "name" => "手机" "sub" => array:2 [ 0 => & array:3 [ "id" => 11 "pid" => 3 "name" => "华为" ] 1 => & array:3 [ "id" => 12 "pid" => 3 "name" => "Vivo" ] ] ]]