Company's product classification there is a table in which the parent classification is identified by mid, and a hierarchical array is required for subsequent operations.
Thought, thought for a moment did not think of not to repeat the method of reading the database or do not need a recursive operation.
Data Source: (data requires one dimension key to be the same as the ID of the corresponding value two-dimensional array)
$items = Array ( 1 => array (' ID ' => 1, ' pid ' => 0, ' name ' => ' Jiangxi Province '),   ; 2 => Array (' ID ' => 2, ' pid ' => 0, ' name ' => ' Heilongjiang province '), 3 => array (' ID ' => 3 , ' PID ' => 1, ' name ' => ' Nanchang '), 4 => array (' ID ' => 4, ' pid ' => 2, ' name ' => ' Harbin City '), 5 => array (' ID ' => 5, ' pid ' => 2, ' name ' => ' Jixi '), 6 =&G T Array (' ID ' => 6, ' PID ' => 4, ' name ' => ' Xiangfang District '), 7 => array (' ID ' => 7, ' PID ' => 4, ' Name ' => ' Nangang '), 8 => array (' ID ' => 8, ' pid ' => 6, ' name ' => ' and Hing Road '), 9 => Array (' ID ' => 9, ' PID ' => 7, ' name ' => ' West big Straight Street '), 10 => array (' id ' = >, ' PID ' => 8, ' name ' => ' Nefu '), 11 => array (' ID ' => one, ' pid ' => 9, ' name "=> ' Harbin Institute of Technology"), 12 => Array (' ID ' =>, ' pid ' => 8, ' name ' => ' Harbin Normal University '), 13 =& Gt Array (' ID ' =>, ' pid ' => 1, ' name ' => ' Ganzhou '), 14 => array (' ID ' =>, ' pid ' => , ' name ' => ' Gan County '), 15 => array (' ID ' =>, ' pid ' =>, ' name ' => ' Yudu '), 16 => Array (' ID ' =>, ' pid ' =>, ' name ' => ' Mao Dian Town '), 17 => Y (' id ' =>, ' pid ' =>, ' name ' => ' da Tian Xiang '), 18 => array (' ID ' =>, ' pid ' => 16 , ' name ' => ' Yi Yuan Village '), 19 => array (' ID ' =>, ' pid ' =>, ' name ' => ' Dam Village ');
function to build tree:
function GenTree9 ($items) {
$tree = array ();
foreach ($items as $item)
if (Isset ($items [$item [' pid ']])
$items [$item [' pid ']][' son '] = &am p; $items [$item [' id ']];
else
$tree [] = & $items [$item [' id ']];
return $tree;
}
Of course. To meet the specific conditions of the data, but also can be reduced to a function of only a few 5 lines:
function GenTree5 ($items) {
foreach ($items as $item)
$items [$item [' pid ']][' son '] [$item [' id ']] = &am p; $items [$item [' id ']];
return Isset ($items [0][' son '])? $items [0][' son ']: Array ();
}
A loop, memory reference. Save time and space.