PHP infinite pole classification assembles clever code into a classification tree
Bags adult
The current classification database design is basically as follows: each classification has an ID primary key field, and a PID points to the ID of the parent class. In this way, infinite classification can be realized, and the data extracted is in the following format:
$arr = array (array (" id "= > 1," pid "= > 0, 'cat' = > 'column a), array (= > 2" id ", "pid" = > 0,' cat '= >' section 2), Array (" id "= > 3," pid "= > 1, 'cat' = > 'section 3), array (" id" = > 4, "pid" = > 2,' the cat '= >' section 4 '), array (" id = "" > 5, "Pid" = > 1, the 'cat' = > 'column 5), array (" id "= > 6," pid "= > 5,' cat '= >' section 6), array (" id" = > 7, "pid" = > 5, 'cat' = > 'section 7'), array (= > 8 "id", "pid" = > 6, 'cat' = > 'column 8'), array (" id "= > 9," pid "= > 1, 'cat' = > 'section 9). Array (" id "= > 10," pid "= > 0, 'cat' = > 'column 10'), array (= > 11" id ", "pid" = > 10, 'cat' = > 'section 11), array (" id "= > 12, "Pid" = > 11, 'cat' = > 'column 12'), array (" id "= > 13," pid "= > 2, 'the cat' = > 'section 13), array (" id" = > 14, "pid" = > 13, 'cat' => 'column 14 ');Copy the code
Without further ado, go straight to the code:
Function make_tree($arr){$refer = array(); $tree = array(); foreach($arr as $k => $v){ $refer[$v['id']] = & $arr[$k]; / / create a primary key of an array reference} foreach ($arr as $k $v) = > {$pid = $v [' pid]; / / get the current classification of the parent id if ($pid = = 0) {$tree [] = & $arr [$k]; / / top section} else {the if (isset ($refer [$pid])) {$refer [$pid] [' subcat] [] = & $arr [$k]; }}} return $tree; }Copy the code
Test run:
$cat = make_tree($arr);
print_r($cat);
Copy the code
Running results:
Array ([0] = > Array ([id] = > 1 [pid] = > 0 (cat) = > columns a [subcat] = > Array ([0] = > Array ([id] = > 3 [pid] = > 1 (cat) = > section 3) [1] = > Array ([id] 5 [pid] = = > > 1 (cat) = > column 5 [subcat] = > Array ([0] = > Array ([id] = > 6 [pid] = > 5 [cat] = > section 6 [subcat] = > Array ([0] = > Array (8 [pid] [id] = > = > 6 (cat) = > column 8))) [1] = > Array ([id] 7 [pid] = = > > 5 [cat] = > section 7))) [2] = > Array ([id] = > 9 [pid] = > 1 (cat) = > section 9))) [1] = > Array ([id] = > 2 [pid] = > 0 (cat) = > Section 2 [subcat] = > Array ([0] = > Array ([id] = > 4 [pid] = > 2 (cat) = > column 4) [1] = > Array ([id] = > 13 [pid] = > 2 (cat) = > Section 13 [subcat] = > Array ([0] = > Array ([id] = > [pid] 13 (cat) = = > > section 14))))) [2] = > Array ([id] = > 10 [pid] = > 0 (cat) = > section 10 [subcat] = > Array ([0] = > Array ([id] 11 [pid] = = > > 10 [cat] = > section 11 [subcat] = > Array ([0] = > Array ([id] 12 [pid] = = > > 11 [cat] = > section 12))))))Copy the code
If you need such an assembly format, or need this format to facilitate subsequent processing, you can try this method, I hope this article can help you
- give a like
- collection
- share
Comments (0 participants)