简体   繁体   中英

PHP - Flattening an 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM