Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through an array with children of children

Tags:

php

laravel-5

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);
        }
    }
}
like image 892
Alvin Bakker Avatar asked Sep 26 '22 09:09

Alvin Bakker


1 Answers

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);
            } 
        }
    }
 }
like image 148
Rafał Cz. Avatar answered Sep 29 '22 05:09

Rafał Cz.