多维数组键合并为单个值

时间:2017-03-30 20:13:05

标签: php arrays

我想让所有多维键合并为输出数组的单个键。我的输入数组如下:

Array
(
    [field1] => test
    [field2] => test
    [field3] => test
    [field4] => Array
        (
            [field5] => test
            [field6] => test
            [field7] => test
            [field8] => test
            [field9] => test
            [field10] => test
            [field11] => test
        )
)

我希望输出如下:

Array
(
    [0] => field1
    [1] => field2
    [2] => field3
    [3] => field4/field5
    [4] => field4/field6
    [5] => field4/field7
    [6] => field4/field8
    [7] => field4/field9
    [8] => field4/field10
    [9] => field4/field11
)

我的代码如下:

function get_data($config_data, $final_arr=array()) {
    foreach($config_data as $key =>$value) {
        if(is_array($value)) {
            $final_arr[]=$key.'=>'.get_data($value, $final_arr[$key]);
        } else {
            $final_arr[]=$key;
        }
    }
    return $final_arr;
} 

1 个答案:

答案 0 :(得分:2)

你需要某种形式的位置标记。看看这个简单的例子:

<?php
$input = [
    'field1' => 'test',
    'field2' => 'test',
    'field3' => 'test',
    'field4' => [
        'field41' => 'test',
        'field42' => 'test',
        'field43' => 'test',
    ],
    'field5' => [
        'field51' => 'test',
        'field52' => [
            'field521' => 'test',
        ],
    ],
    'field6' => 'test',
];
$output = [];
$position = [];
$assembleData = function($data) use (&$assembleData, &$output, &$position) {
    foreach ($data as $key=>$val) {
        array_push($position, $key);
        if (is_array($val)) {
            $assembleData($val);
        } else {
            $output[] = implode('/', $position);
        }
        array_pop($position);
    }
};
$assembleData($input);
print_r($output);

输出是:

Array
(
    [0] => field1
    [1] => field2
    [2] => field3
    [3] => field4/field41
    [4] => field4/field42
    [5] => field4/field43
    [6] => field5/field51
    [7] => field5/field52/field521
    [8] => field6
)