/** * 通过指针实现二维数组转换为树形结构 * @param array $data 数据 * @param string $childrenname 子数据名 * @param string $keyName 数据key名 * @param string $pidName 数据上级key名 * @return array */ function array2Tree(array $data, string $childrenname = 'children', string $keyName = 'id', string $pidName = 'pid'): array { $list = array(); foreach ($data as $value) { $list[$value[$keyName]] = $value; } static $tree = array(); foreach ($list as $item) { if (isset($list[$item[$pidName]])) { $list[$item[$pidName]][$childrenname][] = &$list[$item[$keyName]]; } else { $tree[] = &$list[$item[$keyName]]; } } 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] => 宝安区 ) [1] => Array ( [id] => 4 [pid] => 2 [name] => 南山区 ) ) ) ) ) [1] => Array ( [id] => 10 [pid] => 0 [name] => 浙江 ) ) PS E:\www\shop\branches\shop3> php test4.php 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] => 宝安区 ) [1] => Array ( [id] => 4 [pid] => 2 [name] => 南山区 ) ) [1] => Array ( [id] => 10 [pid] => 0 [name] => 浙江 ) )