/** * 无限级二维数组分类生成树形数据 * @param $menusList * @param int $pid * @param array $navList * @return array */ function array2Tree($arr, $pid = 0) { $tree = []; foreach ($arr as $key => $val) { if ($val['pid'] == $pid) { unset($arr[$key]); $val['children'] = array2Tree($arr, $val['id']); if ($val['children']) { $val['expand'] = true; } $tree[] = $val; } } return $tree; }
测试:
$data = [ [ 'id' => '1', 'pid' => '0', 'name' => '广东' ], [ 'id' => '2', 'pid' => '1', 'name' => '深圳' ], [ 'id' => '3', 'pid' => '2', 'name' => '宝安区' ], [ 'id' => '4', 'pid' => '2', 'name' => '南山区' ], [ 'id' => '10', 'pid' => '0', 'name' => '浙江' ], ]; print_r(array2Tree($data)); Array ( [0] => Array ( [id] => 1 [pid] => 0 [name] => 广东 [children] => Array ( [0] => Array ( [id] => 2 [pid] => 1 [name] => 深圳 [children] => Array ( [0] => Array ( [id] => 3 [pid] => 2 [name] => 宝安区 [children] => Array ( ) ) [1] => Array ( [id] => 4 [pid] => 2 [name] => 南山区 [children] => Array ( ) ) ) [expand] => 1 ) ) [expand] => 1 ) [1] => Array ( [id] => 10 [pid] => 0 [name] => 浙江 [children] => Array ( ) ) )