I want this effect, using iteration
I have this effect now, how can I make the array taken out hierarchical?
How to modify the current code? Or give me some ideas
<code>//迭代调用子孙树 function node_merge($node,$access,$parent = 0){ $task = array($parent) ; //任务表 $arr = array(); //返回数据 while (!empty($task)) { $flag = false; //声明标识符 foreach ($node as $k=> $v) { if($v['pid'] == $parent){ if (isset($node[$parent])) { $arr[] = $v; } // $arr[] = $v; //将找到的栏目存进$arr,等待返回 array_push($task, $v['id']);//将最新的地区存入任务栈,只要task还有任务,循环会继续. $parent = $v['id'];//将当前id存入$parent unset($node[$k]); //把找到的单元unset掉 $flag = true; //说明找到了子栏目 } } //如果flsg为false,就代表找不到已找不到子栏目了,可以将最后的单元pop掉然后继续循环了. if ($flag == false) { array_pop($task); //弹出任务表 $parent = end($task); //把找到的单元unset掉 } } return $arr; } </code>
I want this effect, using iteration
I have this effect now, how can I make the array taken out hierarchical?
How to modify the current code? Or give me some ideas
<code>//迭代调用子孙树 function node_merge($node,$access,$parent = 0){ $task = array($parent) ; //任务表 $arr = array(); //返回数据 while (!empty($task)) { $flag = false; //声明标识符 foreach ($node as $k=> $v) { if($v['pid'] == $parent){ if (isset($node[$parent])) { $arr[] = $v; } // $arr[] = $v; //将找到的栏目存进$arr,等待返回 array_push($task, $v['id']);//将最新的地区存入任务栈,只要task还有任务,循环会继续. $parent = $v['id'];//将当前id存入$parent unset($node[$k]); //把找到的单元unset掉 $flag = true; //说明找到了子栏目 } } //如果flsg为false,就代表找不到已找不到子栏目了,可以将最后的单元pop掉然后继续循环了. if ($flag == false) { array_pop($task); //弹出任务表 $parent = end($task); //把找到的单元unset掉 } } return $arr; } </code>
It shouldn’t be so complicated~
Using recursion can easily accomplish such a task:
Recursion
<code class="php">function parseTree($tree, $root = null) { $nested = array(); foreach($tree as $index => $child) { if($child['pid'] == $root) { unset($tree[$index]); $child['children'] = parseTree($tree, $child['id']); $nested[] = $child; } } return empty($nested) ? null : $nested; }</code>
Iteration
<code class="php">function parseTree($rows) { $rows = array_column ( $rows, null, 'id' ); foreach ( $rows as $key => $val ) { if ( $val ['pid'] ) { if ( isset ( $rows [$val ['pid']] )) { $rows [$val ['pid']]['children'][] = &$rows [$key]; } } } foreach ( $rows as $key => $val ) { if ( $val ['pid'] ) unset ( $rows [$key] ); } return $rows; }</code>