繁体   English   中英

PHP-展平数组

[英]PHP - Flattening an array

我有这样的数组。

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
        )
)

我目前正在为此寻求解决方案。

也许不是“美容”方式,而是类似的东西?

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

您是否需要下层阶级的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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