fork download
  1. <?php
  2.  
  3. function transform_impl($arr, $obj, &$res) {
  4. $res = array();
  5. foreach ($arr as $item) {
  6. $children = @$item['children'];
  7. unset($item['children']);
  8. $res[] = array_merge($obj, $item);
  9. if ($children) {
  10. transform_impl($children, array_merge($obj, $item), $res);
  11. }
  12. }
  13. }
  14.  
  15. function transform($arr) {
  16. $res = array();
  17. transform_impl($arr, array(), $res);
  18. return $res;
  19. }
  20.  
  21. print_r(transform(array(
  22. array("category" => "vegetable", "type" => "garden", "children" =>
  23. array(array("name" => "cabbage"), array("name" => "eggplant"))
  24. ),
  25. array("category" => "fruit", "type" => "citrus")
  26. )));
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
Array
(
    [0] => Array
        (
            [category] => vegetable
            [type] => garden
            [name] => cabbage
        )

    [1] => Array
        (
            [category] => vegetable
            [type] => garden
            [name] => eggplant
        )

    [2] => Array
        (
            [category] => fruit
            [type] => citrus
        )

)