I am trying to create and save an element tree where one element can be a child of another. But this child may also have children, etc. So, for example, I get an array like:
array( [0] array( 'id' => 100 ), [1] array( 'id' => 101, 'children' => array( [0] array( 'id' => 103 ) ) ) )
Or like 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 the code below, I can go one level to find children and perform an action. Of course, I can add another if there are children, but that would mean a lot of if and foreach statements to get to the bottom of the array. Moreover, as I know, sometimes children can go up to 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 use of the code below:
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); } } }