Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 数组值总是被foreach中的最后一个键覆盖_Php_Arrays - Fatal编程技术网

Php 数组值总是被foreach中的最后一个键覆盖

Php 数组值总是被foreach中的最后一个键覆盖,php,arrays,Php,Arrays,有以下数组: $input = [ 'adults' => [1, 2], 'children' => [3, 4] ]; 此数组中的键和值的数量可能是动态的(但结构key=>Numeric:array始终保持不变) 我想将此数组转换为以下结构: [ [ 'adults' => 1, 'children' => 3 ], [ 'adults' => 2, 'children' =&

有以下数组:

$input = [
    'adults' => [1, 2],
    'children' => [3, 4]
];
此数组中的键和值的数量可能是动态的(但结构key=>Numeric:array始终保持不变)

我想将此数组转换为以下结构:

[
   [
      'adults' => 1,
      'children' => 3
   ],

   [
      'adults' => 2,
      'children' => 4
   ]
]
为了实现这一点,我编写了以下函数:

function parse(array $input)
{
    $output = [];

    $keys = array_keys($input);

    foreach ($input as $parameter => $values) {
        $internal = [];

        foreach ($values as $value) {
            foreach ($keys as $key) {
                if (!isset($internal[$key])) {
                    $internal[$key] = $value;
                }
            }
        }

        $output[] = $internal;
    }

    return $output;
}
但这会产生一个意想不到的结果:

print_r(parse($input));

Array
(
    [0] => Array
        (
            [adults] => 1
            [children] => 1
        )

    [1] => Array
        (
            [adults] => 3
            [children] => 3
        )

)

不知何故,这些值总是被解析函数中的最后一个值覆盖。那么,是什么导致了这个错误呢?

如果我正确理解了逻辑,这应该可以:

function parse(array $input)
{
    $output = [];
    foreach ($input as $key1 => $values) {
        foreach ($values as $key2 => $value) {
            $output[$key2][$key1] = $value;
        }
    }
    return $output;
}

有一个更大的数组

$input = [
    'adults' => [1, 2],
    'children' => [3, 4],
    'foo' => [2, 7],
    'bar' => [4, 6],
];
这是回报

Array
(
    [0] => Array
        (
            [adults] => 1
            [children] => 3
            [foo] => 2
            [bar] => 4
        )

    [1] => Array
        (
            [adults] => 2
            [children] => 4
            [foo] => 7
            [bar] => 6
        )

)