lundi 26 octobre 2015

Losing sort order when creating a tree from array

Based on a previous question on how to create a tree from a nested array with parent ID's, I now have an almost completed script. The only thing is that in the output json the ordering is messed up. This is due that the array is now build on parent_id instead of the ordering by database field 'sorting.'

Can any one help me figure out where and how to make a change for it to work, that in the json the item with the lowest number in 'sorting' is listed first?

public function sorting() {
    $pages = Page::orderBy('sorting')->get()->toArray();
    $new = array();
    foreach ($pages as $page){
        $new[$page['parent_id']][] = $page;
    }
    $tree = $this->createTree($new, $new[0]);
    return view('base\backend\pages\sorting', [
        'pages' => json_encode($tree)
    ]);
}

private function createTree(&$list, $parent){
    $tree = array();
    foreach ($parent as $key=>$item){
        if(isset($list[$item['id']])){
            $item['children'] = $this->createTree($list, $list[$item['id']]);
        }
        $tree[] = $item;
    }
    return $tree;
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire