标签:array each ret foreach 索引 tree func 引用 map
<?php $arr= [ ‘0‘=>[ "id"=>2, "name"=>"建材", "pid"=>0, "sort"=>50 ], ‘1‘=>[ "id"=>3, "name"=>"餐厅", "pid"=>1, "sort"=>50 ], ‘2‘=>[ "id"=>1, "name"=>"家居", "pid"=>0, "sort"=>50 ], ‘3‘=>[ "id"=>4, "name"=>"客厅", "pid"=>1, "sort"=>50 ], ]; function genTree($items,$pid ="pid") { $map = []; $tree = []; foreach ($items as &$it){ $map[$it[‘id‘]] = &$it;//数据的ID名生成新的引用索引树 } foreach ($items as &$it){ $parent = &$map[$it[$pid]]; if($parent) { $parent[‘son‘][] = &$it; }else{ $tree[] = &$it; } } return $tree; } echo ‘<pre>‘;var_export(genTree($arr));‘<pre>‘; //array ( // 0 => // array ( // ‘id‘ => 2, // ‘name‘ => ‘建材‘, // ‘pid‘ => 0, // ‘sort‘ => 50, // ), // 1 => // array ( // ‘id‘ => 1, // ‘name‘ => ‘家居‘, // ‘pid‘ => 0, // ‘sort‘ => 50, // ‘son‘ => // array ( // 0 => // array ( // ‘id‘ => 3, // ‘name‘ => ‘餐厅‘, // ‘pid‘ => 1, // ‘sort‘ => 50, // ), // 1 => // array ( // ‘id‘ => 4, // ‘name‘ => ‘客厅‘, // ‘pid‘ => 1, // ‘sort‘ => 50, // ), // ), // ), //)
标签:array each ret foreach 索引 tree func 引用 map
原文地址:http://www.cnblogs.com/719907411hl/p/6918970.html