0

i'm trying to fill data json for treemaker.js from database

My data

now i expected the output of json should be like this:

let tree = { 
    '1': {
        '2': {
            '3': {
                '5': '',
                '6': '',
            },
            '4': {
                '7': '',
                '8': '',
                '9': '',
            },
        },
    },
};

i already tried :

function buildTree(array $elements, $parentId = 0) {
    $branch = [];
    $new = [];
    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = $this->buildTree($elements, $element['id']);
            if ($children) {
                $element[$element['id']] = $children;
            } else {
                $element[$element['id']] = '';
            }
            unset($element["id"]);
            unset($element["root"]);
            unset($element["parent_id"]);
            $branch[] = $element;
        }
    }
    return $branch;
}

public function test($id)
{
    $data = $this->Data_model->getDataByRoot($id)->result_array();
    $tree = $this->buildTree($data);
    echo "<pre>";
    print_r( json_encode($tree, JSON_PRETTY_PRINT|JSON_FORCE_OBJECT));
}

, i get the reference from here

but the result is like this

can you guys show me how to get this done like what i expected ?

thank you

smlos
  • 35
  • 4

0 Answers0