This post was last edited by qq43599939 on 2013-08-28 12:42:25
Array (' ID ' =>1, ' name ' = ' China ', ' pid ' =>0), 1=>array (' id ' =>2, ' name ' = ' ' Beijing ', ' pid ' =>1 ') ; Print_r (Catsort ($area)); function Catsort ($cate, $pid = 0) { $arr = array (); foreach ($cate as $v) { if ($v [' pid '] = = $pid) { $arr [] = $v; $arr = Array_merge ($arr, Catsort ($cate, $v [' ID '])); $arr [] = $v; } } return $arr; } ? >
This question puzzled me, why $arr [] = $v put in $arr = Array_merge ($arr, Catsort ($cate, $v [' ID ']) before returning to China, then Beijing. and put it to $arr = Array_merge ($arr, Catsort ($cate, $v [' ID ']) after the time is Beijing first, after China? Please help explain in detail, thank you
Reply to discussion (solution)
Should you at least read about the book's traversal?
Recursion is traversing a tree
Named according to where the Access node operation occurred:
①NLR: Pre-sequence traversal (Preordertraversal also known as (sequential traversal))
?? The operation to access the root node occurs before the left and right subtrees of the tree are traversed.
②LNR: Middle sequence Traversal (inordertraversal)
?? The operation that accesses the root node occurs in the traversal of its left and right subtree (between).
③LRN: Post-post traversal (postordertraversal)
?? The operation that accesses the root node occurs after the left and right subtrees of the tree are traversed.
$arr [] = $v placed in front of $arr = Array_merge ($arr, Catsort ($cate, $v [' ID ']))
is a pre-order traversal
put to $arr = Array_merge ($arr, Catsort ($cate, $v [' ID '])) behind
is the post-traversal
Then why put in front is the preface, the Back is the post-order, not very understanding, can you speak clearly?
foreach ($cate as $v) { if ($v [' pid '] = = $pid) { $arr [] = $v; $arr = Array_merge ($arr, Catsort ($cate, $v [' ID '])); $arr [] = $v; } }
In front of the time, China first added to the $arr of nothing to say.
foreach ($cate as $v) { if ($v [' pid '] = = $pid) { //$arr [] = $v; $arr = Array_merge ($arr, Catsort ($cate, $v [' ID '])); Here Catsort into recursive $arr [] = $v; } }
In the back, the outer array_merge function handles the second parameter "Catsort ($cate, $v [' id '])", recursively enters the inner layer, executes "$arr []= $v" in the inner layer, adds Beijing to the array before returning to the outer layers, and executes the outer "$ Arr[]= $v ".
Got it, thank.