Skip to content

Instantly share code, notes, and snippets.

@meysampg
Created April 27, 2019 17:10
Show Gist options
  • Select an option

  • Save meysampg/c51fadb37fde78e74e56614f505e54d4 to your computer and use it in GitHub Desktop.

Select an option

Save meysampg/c51fadb37fde78e74e56614f505e54d4 to your computer and use it in GitHub Desktop.
Create a tree from a flat array (like data retrieved from DB)
<?php
// Data from stackoverflow
$a = array(
array('id'=>100, 'parentid'=>0, 'name'=>'a0'),
array('id'=>102, 'parentid'=>101, 'name'=>'a012'),
array('id'=>103, 'parentid'=>101, 'name'=>'a011'),
array('id'=>101, 'parentid'=>100, 'name'=>'a01'),
array('id'=>104, 'parentid'=>100, 'name'=>'a02'),
);
$tree = createTree($a, $a[0]);
print_r($tree);
function createTree(array $a, array $root): array {
$leaf = [
'id' => $root['id'],
'name' => $root['name'],
'children' => [],
];
foreach ($a as $node) {
if ($node['parentid'] == $root['id']) {
$leaf['children'][] = createTree($a, $node);
}
}
return $leaf;
}
@meysampg
Copy link
Author

meysampg@freedom:/srv/http/test 
$ php makeTreeFromArray.php
Array
(
    [id] => 100
    [name] => a0
    [children] => Array
        (
            [0] => Array
                (
                    [id] => 101
                    [name] => a01
                    [children] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 102
                                    [name] => a012
                                    [children] => Array
                                        (
                                        )

                                )

                            [1] => Array
                                (
                                    [id] => 103
                                    [name] => a011
                                    [children] => Array
                                        (
                                        )

                                )

                        )

                )

            [1] => Array
                (
                    [id] => 104
                    [name] => a02
                    [children] => Array
                        (
                        )

                )

        )

)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment