lundi 26 octobre 2015

Looping through an array with children of children

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire