Read the catalog to generate a two-dimensional array under the top-level category that contains other classifications under the top level
But a two-dimensional array under the next top-level category will contain the value of the previous top-level as if it were a static declaration variable, but I don't know how to release it. The following is a reason to ask:
Picture description
Reply content:
Read the catalog to generate a two-dimensional array under the top-level category that contains other classifications under the top level
But a two-dimensional array under the next top-level category will contain the value of the previous top-level as if it were a static declaration variable, but I don't know how to release it. The following is a reason to ask:
Picture description
Look again, the following should be able to meet the requirements.
Array (' ID ' =>1, ' pid ' =>0, ' 2 ' =>array (' id ' =>2, ' pid ' =>0, '), ' 3 ' =>array (' id ') =>3, ' pid ' =>1, ' 4 ' =>array (' id ' =>4, ' pid ' =>2, '), ' 5 ' =>array (' id ' =>5, ' p Id ' =>4 ', ' 6 ' =>array (' id ' =>6, ' pid ' =>5, '), ' 7 ' =>array (' id ' =>7, ' pid ' =>3), ' 8 ' =>array (' id ' =>8, ' pid ' =>4, '), ' 9 ' =>array (' id ' =>9, ' pid ' =>7),); /format foreach with ID key ($arr as $key + $value) {$list [$value [' id ']]= $value;} Iterate over the array foreach ($list as $key + $value) {if ($value [' pid ']==0) {$tree [$value] [' id ']]= $value; }else{//ancestor ID $ancestor _id= "; Determine if there is no corresponding value in the ancestor array, then remove if (!empty ($ancestor [$value [' pid]]) {$ancestor _id= $ancestor [$value [' pid ']]; }else{$topid = $value [' id ']; $child =array (); if (Empty ($ancestor [$topid])) {$child []= $topid; }//Through the loop, one layer at a level to find their respective fathers, until their fathers while ($list [$topid] [' pid '] > 0) { $topid = $list [$topid] [' pid ']; if (empty ($topid)) {$topid = '; Break }else{///ancestor array if not, then put the descendant array if (Empty ($ancestor [$topid])) { $child []= $topid; }else{//ancestors already exist, there is no need to cycle down $topid = $ancestor [$topid]; Break }}} $ancestor _i D= $topid; If the ancestor is found, the descendants array is added to the ancestor array if (!empty ($ancestor _id)) {foreach ($child as $k = = $v) { $ancestor [$v]= $ancestor _id; } }} if (!empty ($ancestor _id)) {$tree [$ancestor _id][' child '] [$value [' id ']]= $value; }}}echo '
';var_dump($tree);