<?php $arrData= array( array( "id" => "1", "pid" => "0", "name" => "山东" ), array( "id" => "2", "pid" => "0", "name" => "云南" ), array( "id" => "3", "pid" => "1", "name" => "济南" ), array( "id" => "4", "pid" => "2", "name" => "大理" ), array( "id" => "7", "pid" => "3", "name" => "历下区" ), array( "id" => "8", "pid" => "7", "name" => "大明湖" ), array( "id" => "9", "pid" => "1", "name" => "青岛" ), array( "id" => "10", "pid" => "3", "name" => "**县" ), ); $arrReData = array(); $result = array(); foreach($arrData as &$data){ $arrReData[$data["id"]] = $data; if($data["pid"]!="0" && isset($arrReData[$data["pid"]])){ if(!isset($arrReData[$data["pid"]]["children"])){ $arrReData[$data["pid"]]["children"] = array(); } $arrReData[$data["pid"]]["children"][] = &$arrReData[$data["id"]]; }else{ $result[] = &$arrReData[$data["id"]]; } } print_r($result);
Array ( [0] => Array ( [id] => 1 [pid] => 0 [name] => 山东 [children] => Array ( [0] => Array ( [id] => 3 [pid] => 1 [name] => 济南 [children] => Array ( [0] => Array ( [id] => 7 [pid] => 3 [name] => 历下区 [children] => Array ( [0] => Array ( [id] => 8 [pid] => 7 [name] => 大明湖 ) ) ) [1] => Array ( [id] => 10 [pid] => 3 [name] => **县 ) ) ) [1] => Array ( [id] => 9 [pid] => 1 [name] => 青岛 ) ) ) [1] => Array ( [id] => 2 [pid] => 0 [name] => 云南 [children] => Array ( [0] => Array ( [id] => 4 [pid] => 2 [name] => 大理 ) ) ) )