1

I have an array like this.

Array
(
    [0] => Array
        (
            [category] => vegetable
            [type] => garden
            [children] => Array
                (
                    [0] => Array
                        (
                            [name] => cabbage
                        )

                    [1] => Array
                        (
                            [name] => eggplant
                        )

                )

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

What is an easy way to construct a resulting array like this using PHP?

Array
(
    [0] => Array
        (
            [category] => vegetable
            [type] => garden
            [name] => cabbage
        )
    [1] => Array
        (
            [category] => vegetable
            [type] => garden
            [name] => eggplant
        )
    [2] => Array
        (
            [category] => fruit
            [type] => citrus
        )
)

I am currently working on a solution for this.

Jake
  • 25,479
  • 31
  • 107
  • 168
  • 1
    possible duplicate of [How to "flatten" a multi-dimensional array to simple one in PHP?](http://stackoverflow.com/questions/526556/how-to-flatten-a-multi-dimensional-array-to-simple-one-in-php) – Marin Atanasov Sep 29 '14 at 19:57
  • @MarinAtanasov That doesn't seem to be a case. There was no associative arrays there. – polkovnikov.ph Sep 29 '14 at 20:03

2 Answers2

1

Maybe not the 'beauty' way, but just something like this?

$newArray = array();    

foreach($currentArray as $item)
{
    if(!empty($item['children']) && is_array($item['children']))
    {
        foreach($item['children'] as $children)
        {
            $newArray[] = array( 'category'=>$item['category'] , 'type'=>$item['type'] , 'name'=>$children['name']);
        }
    }
    else
    {
        $newArray[] = array( 'category'=>$item['category'] , 'type'=>$item['type']);
    }
}
S.Pols
  • 3,414
  • 2
  • 21
  • 42
1

Do you need children down on your hierarchy?

<?php

function transform_impl($arr, $obj, &$res) {
    $res = array();
    foreach ($arr as $item) {
        $children = @$item['children'];
        unset($item['children']);
        $res[] = array_merge($obj, $item);
        if ($children) {
            transform_impl($children, array_merge($obj, $item), $res);
        }
    }
}

function transform($arr) {
    $res = array();
    transform_impl($arr, array(), $res);
    return $res;
}

print_r(transform(array(
    array("category" => "vegetable", "type" => "garden", "children" =>
        array(array("name" => "cabbage"), array("name" => "eggplant"))
    ),
    array("category" => "fruit", "type" => "citrus")
)));

Live version: http://ideone.com/0wO4wU

polkovnikov.ph
  • 6,256
  • 6
  • 44
  • 79