Search code examples
phparraysmultidimensional-arrayparent-child

Distribute child elements from a multidimensional array as rows including parent values in a new 2d array


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.


Solution

  • 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']);
        }
    }