Skip to content

Instantly share code, notes, and snippets.

@dailybird
Created June 2, 2017 00:17
Show Gist options
  • Save dailybird/3fb1590b9836383ae0181c470f4096e6 to your computer and use it in GitHub Desktop.
Save dailybird/3fb1590b9836383ae0181c470f4096e6 to your computer and use it in GitHub Desktop.
Resolve nodes to tree.
<?php
/**
* Created by PhpStorm.
* User: dailybird
* Date: 17/6/1
* Time: 下午11:57
*/
$nodes = [
[
'id' => 5,
'parent_id' => 2
],
[
'id' => 2,
'parent_id' => 1
],
[
'id' => 3,
'parent_id' => 1
],
[
'id' => 1,
'parent_id' => -1
],
[
'id' => 6,
'parent_id' => 4
],
[
'id' => 8,
'parent_id' => 7
],
[
'id' => 9,
'parent_id' => 7
],
[
'id' => 7,
'parent_id' => 4
],
[
'id' => 10,
'parent_id' => 4
],
[
'id' => 4,
'parent_id' => -1
],
];
function resolveNodesToTree(&$tree, &$nodes, $parentNode)
{
foreach ($nodes as $index => $node) {
if($node['parent_id'] === $parentNode){
$foo = resolveNodesToTree($tree[$node['id']], $nodes, $node['id']);
if(!is_null($foo)){
$node['children'] = $foo;
$tree[] = $node;
unset($nodes[$index]);
}else{
unset($tree[$node['id']]);
}
}
}
return $tree;
}
const ROOT_NODE = -1;
$tree = [];
resolveNodesToTree($tree, $nodes, ROOT_NODE);
print_r(json_encode($tree));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment