如何将第一级键与其第二级值合并并删除所有关联键?

时间:2018-03-20 04:14:51

标签: php multidimensional-array indexing array-merge

我有这样的数组:

Array (
    [2018-03-12] => Array (
        [United States] => 4
        [Australia] => 15
        [United Kingdom] => 0
        [New Zealand] => 0
    )
    [2018-03-13] => Array (
        [United States] => 0
        [Australia] => 8
        [United Kingdom] => 2
        [New Zealand] => 0
    )
)

我想制作一个这样的数组:

[
    ["2018-03-12", 4, 15, 0, 0],
    ["2018-03-13", 0, 8, 0, 2]
]

如何做到这一点?

2 个答案:

答案 0 :(得分:5)

尝试:

$arr = [
    '2018-03-12' => [
        'United States' => 4,
         'Australia' => 15,
         'United Kingdom' => 0,
         'New Zealand' => 0,
    ],
    '2018-03-13' => [
         'United States' => 0,
         'Australia' => 8,
         'United Kingdom' => 2,
         'New Zealand' => 0,
    ]
];

return array_map(function ($item, $key) {
    return array_merge([$key], array_values($item));
},$arr, array_keys($arr));

演示https://implode.io/K8yHG0

答案 1 :(得分:0)

您只需要迭代每个顶级元素,然后将键合并/存储为元素和子数组值。

代码:(Demo

$array = [
    '2018-03-12' => [
         'United States' => 4,
         'Australia' => 15,
         'United Kingdom' => 0,
         'New Zealand' => 0,
    ],
    '2018-03-13' => [
         'United States' => 0,
         'Australia' => 8,
         'United Kingdom' => 2,
         'New Zealand' => 0,
    ]
];

foreach ($array as $key => $subarray) {
        $result[] = array_merge([$key], array_values($subarray));
}
var_export($result);

输出:

array (
  0 => 
  array (
    0 => '2018-03-12',
    1 => 4,
    2 => 15,
    3 => 0,
    4 => 0,
  ),
  1 => 
  array (
    0 => '2018-03-13',
    1 => 0,
    2 => 8,
    3 => 2,
    4 => 0,
  ),
)

或者您可以将密钥移至子阵列并重新索引两个级别。

foreach ($array as $key => $subarray) {
    array_unshift($subarray, $key);
    $result[] = array_values($subarray);
}

或者您可以使用Union运算符将键与子阵列元素合并,然后重新编制索引。

foreach ($array as $key => $subarray) {
    $result[] = array_values([$key] + $subarray);
}

如果你的php版本允许可变参数,你甚至可以将子数组解压缩到array_push调用中。

foreach ($array as $key => $subarray) {
    $temp = [];
    array_push($temp, $key, ...array_values($subarray));
    $result[] = $temp;
}