Surfoo
Surfoo

Reputation: 88

Node link Tree and data populate by PHP in json file

I use the Nested set Model from here : http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ and the query from the Depth of a Sub-Tree section.

I would like to use this graph http://bl.ocks.org/mbostock/4339184 with data from my database but I don't know how to design the algorithm in PHP to write json data. The flare.json is here http://bl.ocks.org/mbostock/raw/4063550/flare.json (I don't use the size attribute)

I wrote some code, but I'm lost and I don't know what to do :

$subtree = array(
  ['name' => 'ELECTRONICS',             'depth' => 0],
  ['name' =>    'TELEVISIONS',          'depth' => 1],
  ['name' =>        'TUBE',             'depth' => 2],
  ['name' =>        'LCD',              'depth' => 2],
  ['name' =>        'PLASMA',           'depth' => 2],
  ['name' =>    'PORTABLE ELECTRONICS', 'depth' => 1],
  ['name' =>        'MP3 PLAYERS',      'depth' => 2],
  ['name' =>            'FLASH',        'depth' => 3],
  ['name' =>        'CD PLAYERS',       'depth' => 2],
  ['name' =>        '2 WAY RADIOS',     'depth' => 2],
);

function buildTree($data) {
    $tree    = [];
    $current = 0;

    foreach ($data as $key => $child) {
        // Root
        if ($key == $current) {
            $tree['name'] = $child['name'];
            $lastLevel    = $child['depth'];
        // Child
        } elseif( && $child['depth'] == ($lastLevel + 1)) {
            if (!isset($tree['children'])) {
                $tree['children'] = [];
            }
            $tree['children'][] = buildTree(array_slice($data, $key));
            $current++;
        }
    }

    return $tree;
}

$tree = buildTree($subtree);

print_r($tree);

Thank you very much for your help!

Upvotes: 0

Views: 571

Answers (1)

RuBa Zeibak
RuBa Zeibak

Reputation: 26

You need to be able to stop the recursive loop when you reach a "non-child" by returning the result so far. Also you do not need the $current, as in each recursive loop your array is sliced and the first $key is always 0:

function buildTree($data) {

    $tree    = array();

    foreach ($data as $key => $child) {
        // Root
        if ($key == 0){
            $tree['name'] = $child['name'];
            $lastLevel    = $child['depth'];
        // Child
        } else if(($child['depth'] == ($lastLevel + 1))) {
            if (!isset($tree['children'])) {
                $tree['children'] = array();
            }
            $tree['children'][] = buildTree(array_slice($data,$key));
        }
        else if($child['depth'] <= ($lastLevel)){
            return $tree;
        }
    }
    return $tree;
}

$tree = buildTree($subtree);

print_r($tree);

Upvotes: 1

Related Questions