<?php$arrdata= Array ("id" = "1", "pid" = "0", "name" and "Shandong"), Array ("id" = "2", "pid" = "0", "name" = "Yunnan"), Array ("id" = "3", "pid" = "1", "name" = "Jinan"), Array ("ID" = "4", "pid" = "2", "name" = "Dali"), Array ("id" = "7", "pid" = "3", "name" = "Lixia District"), Array ("id" = "8 "," pid "=" 7 "," name "=" Daming Lake "), Array (" id "=" 9 "," pid "=" 1 "," name "=" Qingdao "), Array (" id "=" ten "," pid " = "3", "name" = "* * County"), $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] = Shandong [Children] = = Array ([0] = = Array ( [id] = 3 [PID] + 1 [name] = Jinan [Children] = = Array ([0] = = Array ([id] = 7 [PID] = 3 [name] = Lixia District [children] = = Array ( [0] = = Array ( [ID] => 8 [PID] = 7 [Name] = Daming Lake) )) [1] = = Array ([id] = 10 [PID] + 3 [name] = * County) )) [1] = = Array ( [id] = 9 [PID] + 1 [name] = Qingdao ))) [1] = = Array ([id] + 2 [pid] = 0 [Name] => Yunnan [Children] = = Array ([0] = = Array ( [id] = 4 [PID] + 2 [name] = Dali ) ) ))
Database data becomes tree-structured