<?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] => 大理 ) ) ) )