PHP-扁平阵列

问题描述 投票:0回答:3

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

php
3个回答
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")
)));


0
投票
© www.soinside.com 2019 - 2025. All rights reserved.