PHP obtains the implementation code of the N-layer Classification Tree from a two-dimensional array.
The company's product category exists in a table and its parent category is identified by mid. You need to obtain an array with a hierarchical structure for subsequent operations.
After thinking about it, I thought about not reading the database repeatedly or having to perform recursive operations.
Data source: (the data requires that the id of the one-dimensional key and the corresponding value two-dimensional array be the same)
$ Items = array (1 => array ('id' => 1, 'pid '=> 0, 'name' => 'jiangxi '), 2 => array ('id' => 2, 'pid '=> 0, 'name' => 'heilongjiang province '), 3 => array ('id' => 3, 'pid '=> 1, 'name' => 'nanchang City '), 4 => array ('id' => 4, 'pid '=> 2, 'name' => 'harbin '), 5 => array ('id' => 5, 'pid '=> 2, 'name' => 'jixi City '), 6 => array ('id' => 6, 'pid '=> 4, 'name' => 'xiangfang Region '), 7 => array ('id' => 7, 'pid '=> 4, 'name' => 'nangang '), 8 => array ('id' => 8, 'pid '=> 6, 'name' =>' and xinglu '), 9 => array ('id' => 9, 'pid '=> 7, 'name' => 'westbrook Street '), 10 => array ('id' => 10, 'pid '=> 8, 'name' => 'northeast forestry Emy '), 11 => array ('id' => 11, 'pid '=> 9, 'name' => 'harbin Institute of Technology '), 12 => array ('id' => 12, 'pid '=> 8, 'name' => 'harbin Normal University '), 13 => array ('id' => 13, 'pid '=> 1, 'name' => 'ganzhou City '), 14 => array ('id' => 14, 'pid '=> 13, 'name' => 'ganxian '), 15 => array ('id' => 15, 'pid '=> 13, 'name' => 'yudu County '), 16 => array ('id' => 16, 'pid '=> 14, 'name' => 'moudian Zhen '), 17 => array ('id' => 17, 'pid' => 14, 'name' => 'tagname '), 18 => array ('id' => 18, 'pid '=> 16, 'name' => 'yiyuan cune '), 19 => array ('id' => 19, 'pid '=> 16, 'name' => 'shangba cune '),);
Generation tree functions:
function genTree9($items) { $tree = array(); foreach ($items as $item) if (isset($items[$item['pid']])) $items[$item['pid']]['son'][] = &$items[$item['id']]; else $tree[] = &$items[$item['id']]; return $tree;}
Of course. Data that meets specific conditions can be scaled to only five rows of a function:
function genTree5($items) { foreach ($items as $item) $items[$item['pid']]['son'][$item['id']] = &$items[$item['id']]; return isset($items[0]['son']) ? $items[0]['son'] : array();}
The memory is referenced in a loop. Saves time and space.