如何在php中按键合并数组数组?

时间:2015-04-09 20:52:00

标签: php arrays

所以这种性质的问题在堆栈溢出时已被问过1000次,但到目前为止我所搜索过的问题都没有解决我遇到的问题。我有两个这样的数组:

$cupcake_sales = [
   ['date' => '05/09/1992', 'num_cupcakes_sold' => 30 ],
   ['date' => '05/11/1992', 'num_cupcakes_sold' => 25 ],
];

和另一个这样的数组:

$cupcake_revenue = [
    ['date' => '05/10/1992', 'revenue' => '$40'],
    ['date' => '05/11/1992', 'revenue' => '$100'],
];

我需要的是这样的数组:

$cupcake_sales_revenue = [
    ['date' => '05/09/1992', 'num_cupcakes_sold' => 30],
    ['date' => '05/10/1992', 'num_cupcakes_sold' => 25, 'revenue' => '$40'], 
    ['date' => '05/11/1992', 'revenue' => '$100'],
];

这样做有什么好办法吗?

1 个答案:

答案 0 :(得分:4)

这应该适合你:

(这里我只使用array_map()遍历两个数组,如果日期相同,我将2个数组与array_merge()合并,并将其分配给结果数组。如果它们不同我只是在当前迭代中将两个数组附加到结果数组。)

<?php

    $cupcake_sales_revenue = [];

    array_map(function($v1, $v2)use(&$cupcake_sales_revenue){
        if($v1["date"] == $v2["date"]) {
            $cupcake_sales_revenue[] = array_merge($v1, $v2);
        } else {
            $cupcake_sales_revenue[] = $v1;
            $cupcake_sales_revenue[] = $v2;
        }
    }, $cupcake_sales, $cupcake_revenue);

    print_r($cupcake_sales_revenue);


?>

输出:

Array
(
    [0] => Array
        (
            [date] => 05/09/1992
            [num_cupcakes_sold] => 30
        )

    [1] => Array
        (
            [date] => 05/10/1992
            [revenue] => $40
        )

    [2] => Array
        (
            [date] => 05/11/1992
            [num_cupcakes_sold] => 25
            [revenue] => $100
        )

)