数据库数据变成树型结构
<?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] => 大理 ) ) ) )
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。