fork download
  1. <?php
  2.  
  3. $array = [
  4. 'a' => ['children' => ['b', 'c']],
  5. 'b' => ['children' => ['ba', 'bb']],
  6. 'c' => ['children' => []],
  7. 'ba' => ['children' => []],
  8. 'bb' => ['children' => ['bba']],
  9. 'bba' => ['children' => []]
  10. ];
  11.  
  12. function expand(&$source, $item) {
  13. $result = ['children' => $item['children']];
  14.  
  15. foreach($item['children'] as $key) {
  16. $result[$key] = expand($source, $source[$key]);
  17. $source[$key] = [];
  18. }
  19.  
  20. return $result;
  21. }
  22.  
  23. foreach($array as $key => $value) {
  24. if(!empty($array[$key])) {
  25. $result[$key] = expand($array, $value);
  26. }
  27. }
  28.  
  29. print_r($result);
Success #stdin #stdout 0s 82880KB
stdin
Standard input is empty
stdout
Array
(
    [a] => Array
        (
            [children] => Array
                (
                    [0] => b
                    [1] => c
                )

            [b] => Array
                (
                    [children] => Array
                        (
                            [0] => ba
                            [1] => bb
                        )

                    [ba] => Array
                        (
                            [children] => Array
                                (
                                )

                        )

                    [bb] => Array
                        (
                            [children] => Array
                                (
                                    [0] => bba
                                )

                            [bba] => Array
                                (
                                    [children] => Array
                                        (
                                        )

                                )

                        )

                )

            [c] => Array
                (
                    [children] => Array
                        (
                        )

                )

        )

)