create array tree from array list create array tree from array list arrays arrays

create array tree from array list


oke this is how i solved it:

$arr = array(  array('id'=>100, 'parentid'=>0, 'name'=>'a'),  array('id'=>101, 'parentid'=>100, 'name'=>'a'),  array('id'=>102, 'parentid'=>101, 'name'=>'a'),  array('id'=>103, 'parentid'=>101, 'name'=>'a'),);$new = array();foreach ($arr as $a){    $new[$a['parentid']][] = $a;}$tree = createTree($new, array($arr[0]));print_r($tree);function createTree(&$list, $parent){    $tree = array();    foreach ($parent as $k=>$l){        if(isset($list[$l['id']])){            $l['children'] = createTree($list, $list[$l['id']]);        }        $tree[] = $l;    }     return $tree;}


small fix if you need more than 1 parentid[0] element :)

$arr = array(  array('id'=>100, 'parentid'=>0, 'name'=>'a'),  array('id'=>101, 'parentid'=>100, 'name'=>'a'),  array('id'=>102, 'parentid'=>101, 'name'=>'a'),  array('id'=>103, 'parentid'=>101, 'name'=>'a'),);$new = array();foreach ($arr as $a){    $new[$a['parentid']][] = $a;}$tree = createTree($new, $new[0]); // changedprint_r($tree);function createTree(&$list, $parent){    $tree = array();    foreach ($parent as $k=>$l){        if(isset($list[$l['id']])){            $l['children'] = createTree($list, $list[$l['id']]);        }        $tree[] = $l;    }     return $tree;}


One more rework of Thunderstriker's variant - all the logic in one function:

/** * @param array $flatList - a flat list of tree nodes; a node is an array with keys: id, parentID, name. */function buildTree(array $flatList){    $grouped = [];    foreach ($flatList as $node){        $grouped[$node['parentID']][] = $node;    }    $fnBuilder = function($siblings) use (&$fnBuilder, $grouped) {        foreach ($siblings as $k => $sibling) {            $id = $sibling['id'];            if(isset($grouped[$id])) {                $sibling['children'] = $fnBuilder($grouped[$id]);            }            $siblings[$k] = $sibling;        }        return $siblings;    };    return $fnBuilder($grouped[0]);}// Example:$flat = [    ['id' => 100, 'parentID' => 0, 'name' => 'root'],    ['id' => 101, 'parentID' => 100, 'name' => 'ch-1'],    ['id' => 102, 'parentID' => 101, 'name' => 'ch-1-1'],    ['id' => 103, 'parentID' => 101, 'name' => 'ch-1-2'],];$tree = buildTree($flat, 'parentID', 'id');echo json_encode($tree, JSON_PRETTY_PRINT);

Playground: https://www.tehplayground.com/Ap4uUuwHWl9eiJIx