从数据表里取得一组二维数组,每个元素有键为 id 和 pid 的值,在不使用递归的情况下,如何按照其 pid 的值将元素移入到相应 id 元素中成为其子元素?
array(6) { [0] => array(3) { ["id"] => "21" ["pid"] => "0" ["name"] => "aaa" } [1] => array(3) { ["id"] => "22" ["pid"] => "0" ["name"] => "bbb" } [2] => array(3) { ["id"] => "23" ["pid"] => "0" ["name"] => "ccc" } [3] => array(3) { ["id"] => "24" ["pid"] => "23" ["name"] => "ddd" } [4] => array(3) { ["id"] => "25" ["pid"] => "23" ["name"] => "eee" } [5] => array(3) { ["id"] => "26" ["pid"] => "22" ["name"] => "fff" } }
重新排列为
array(3) { [0] => array(3) { ["id"] => "21" ["pid"] => "0" ["name"] => "aaa" } [1] => array(4) { ["id"] => "22" ["pid"] => "0" ["name"] => "bbb" ["child"]=> array(1) { [0] => array(3) { ["id"] => "26" ["pid"] => "22" ["name"] => "fff" } } } [2] => array(4) { ["id"] => "23" ["pid"] => "0" ["name"] => "ccc" ["child"]=> array(2) { [0] => array(3) { ["id"] => "24" ["pid"] => "23" ["name"] => "ddd" } [1] => array(3) { ["id"] => "25" ["pid"] => "23" ["name"] => "eee" } } } }
涉及层级关系只有两层。
我想学算法的时候应该有讲过如何把递归改成循环实现。
一般递归都可以用队列+循环来实现,你先想想,空了来写程序。
你这个本来就是该循环实现的,哪里需要递归啊……
没得PHP的环境,用JS给你写个
输出
非常感谢诸位的解答。看了你们的答案还在消化。基础不扎实还要多学习。
自己参考了一下隔壁问题。实现的代码如下:
取值生成变量步骤有点多余,foreach 部分更新如下:
先算出每个数组的顶级pid,然后再排序下。