Looping through an array with children of children

2019-06-22 09:18发布

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
            )
        )
    )
)

Or as 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}]}]

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);
        }
    }
}

标签: php laravel-5
1条回答
时光不老,我们不散
2楼-- · 2019-06-22 09:56

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);
            } 
        }
    }
 }
查看更多
登录 后发表回答