带孩子的孩子循环遍历数组 [英] Looping through an array with children of children

查看:76
本文介绍了带孩子的孩子循环遍历数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作和保存一棵树,其中一个项目可以是另一个项目的子项.但是这个孩子也可以有孩子等.因此,例如,我得到一个像这样的数组:

I am trying to make and save a tree of items where one item can be a child of another. But this child can also have children etc etc. So for instance I am getting an array like:

array(
    [0] array(
        'id' => 100
    ),
    [1] array(
        'id' => 101,
        'children' => array(
            [0] array(
                'id' => 103
            )
        )
    )
)

或作为JSON:

[{"id":1},{"id":3,"children":[{"id":4},{"id":5},{"id":6}]},{"id":2},{"id":7,"children":[{"id":8},{"id":9}]},{"id":10,"children":[{"id":11},{"id":12}]}][{"id":1},{"id":3,"children":[{"id":4},{"id":5},{"id":6}]},{"id":2},{"id":7,"children":[{"id":8},{"id":9}]},{"id":10,"children":[{"id":11},{"id":12}]}]

使用以下代码,我可以更深入地找到孩子并执行操作.当然,我可以添加另一个if有子对象,但这将意味着很多if和foreach语句到达数组的底部.尤其是据我所知,有时候孩子在实践中可以深入到10个层次.

With below code I can go one level deep to find children and perform an action. Of course I can add another if has children, but that would mean a whole lot of if and foreach statements to get to a bottom of the array. Especially as I know sometimes children can go like 10 levels deep in practice.

public function sortPages(Request $request) {
    $data = json_decode($request->data);
    foreach($data as $sort=>$id) {
        $this->saveSortingOrder($id->id, $sort);
        if(isset($id->children)) {
            foreach($id->children as $sort_next=>$id_next) {
                $this->saveSortingOrder($id_next->id, $sort_next);
                $this->setParent($id_next->id, $id->id);
            }
        }
    }
}

有没有简单的方法可以完成工作?

Is there an easy way to get the job done?

使用以下代码修复了该问题:

Fixed it using below code:

public function sortPages(Request $request) {
    $data = json_decode($request->data);
    foreach($data as $sort_value=>$id) {
        $this->saveSortingOrder($id->id, $sort_value);
        if(isset($request->parent)) {
            $this->setParent($id->id, $request->parent);
        }
        if(isset($id->children)) {
            $new_request = new Request;
            $new_request->data = json_encode($id->children);
            $new_request->parent = $id->id;
            $this->sortPages($new_request);
        }
    }
}

推荐答案

递归将很有帮助.这是一个示例:

Recursion will be helpfull. Here is an example:

private function checkArrayRecursively($arr) 
{
    if ($arr) {
        foreach ($arr as $value) {
            if (is_array($value)) {
                // do something
                checkArrayRecursively($value);
            } 
        }
    }
 }

这篇关于带孩子的孩子循环遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆