简体   繁体   English

如何在php中通过键合并数组数组?

[英]How to merge array of arrays by key in php?

So questions of this nature have been asked 1000 times on stack overflow, but none of them I've searched through so far address the issue that I'm having. 因此,在堆栈溢出时已经询问了1000次这种性质的问题,但是到目前为止,我搜索的所有问题都没有解决我遇到的问题。 I have two arrays like this: 我有两个像这样的数组:

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

and another array like this: 和另一个像这样的数组:

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

what I need is an array like this: 我需要的是一个像这样的数组:

$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'],
];

any good way of doing this? 有什么好办法吗?

This should work for you: 这应该为您工作:

(Here I just loop through both arrays with array_map() and if the date is the same I merge the 2 arrays together with array_merge() and assign it to the results array. If they are different I just append both arrays to the result array in the current iteration.) (在这里,我只使用array_map()遍历两个数组,如果日期相同,则将两个数组与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);


?>

output: 输出:

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
        )

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM