PHP - 展平数组

时间:2014-09-29 19:56:17

标签: php

我有这样的数组。

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

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

                )

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

使用PHP构建这样的结果数组的简单方法是什么?

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

我目前正在为此制定解决方案。

2 个答案:

答案 0 :(得分:1)

也许不是'美女'方式,但只是这样的事情?

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

答案 1 :(得分:1)

您的层次结构需要children吗?

<?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")
)));

实时版:http://ideone.com/0wO4wU