如何以给定格式格式化多维数组

时间:2016-12-02 10:04:50

标签: php arrays

我有一个带有一些键的数组,这里我需要的是在相同的键上合并值,例如,键117和&的记分卡值。 107应该在输出数组中合并如下所示。

$input_array = array (

38 => array
    (
        117 => array
            (
                'scorecard' => array
                    (
                        0 => 'q4'
                    ),

                'business_plan' => array
                    (
                        0 => 'q4'
                    )
            ),

        107 => array
            (
                'scorecard' => array
                    (
                        0 => 'q1'
                    ),

                'business_plan' => array
                    (
                        0 => 'q2'
                    )
            ),

    ),

53 => array
    (
        373 => array
            (            
                'scorecard' => array
                    (
                        0 => 'q4'
                    ),

                'business_plan' => array
                    (
                        0 => 'q1'
                    )
            ),

        110 => array
            (       
                'scorecard' => array
                    (
                        0 => 'q4',
                        0 => 'q3'
                    ),

                'business_plan' => array
                    (
                        0 => 'q4'
                    ),

                'marketing_plan' => array
                    (
                        0 => 'q3',
                        1 => 'q4'
                    )

            )

    ),

318 => array
    (
        2279 => array
            (             
                'scorecard' => array
                    (
                        0 => 'q4'
                    )
            )

    )

 );

输出数组将包含如下值: -

 Array
 (
[38] => Array
    (
     [scorecard] => Array
                    (
                        [0] => q4
                        [1] => q1
                    )
     [business_plan] => Array
                    (
                        [0] => q4
                        [1] => q2
                    )            
    )

[53] => Array
    (

        [scorecard] => Array
            (
                 [0] => q4
                 [1] => q3
            )

        [business_plan] => Array
            (
                [0] => q1
                [0] => q4
            )
        [marketing_plan] => Array
            (
                [0] => q3
                [1] => q4
            )
    )

[318] => Array
    (
        [scorecard] => Array
            (
                [0] => q4
            )        
    )

 )

1 个答案:

答案 0 :(得分:2)

可以通过合并array_maparray_reducearray_merge_recursive来完成:

$result = array_map(function ($item) {
    return array_reduce($item, 'array_merge_recursive', []);
}, $input_array);

这是working demo