数组合并和总计(如果相同) [英] array merge and total if it the same keys

查看:77
本文介绍了数组合并和总计(如果相同)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

$A = array("EUR"=>10, "USD"=>20)
$B = array("EUR"=>10, "JPY"=>20)

我要合并并求和具有相同键的值。

I want to merge and sum the the value which have the same keys.

$C = array(
    "EUR" => array(10,10),
    "JPY" => 20,
    "USD" => 20,
)

任何人都可以告诉我该怎么做吗?

Anyone can tell me how to do that?

推荐答案

使用以下代码:

<?php
$A = array("EUR"=>10,"USD"=>20);
$B = array("EUR"=>10,"JPY"=>20);

$C = $A;
foreach ($B as $key => $value) {
    if (isset($C[$key])) {
        $C[$key] = $C[$key] + $value;
    } else {
        $C[$key] = $value;
    }
}

结果将是以下数组:

array(3) {
  ["EUR"] => int(20)
  ["USD"] => int(20)
  ["JPY"] => int(20)
}

它已经计算出了总和。作为证明,请查看 http://codepad.org/Aay0bEh9

It already calculates the sum. For proof look at http://codepad.org/Aay0bEh9.

如果您确实希望结果数组$ C中EUR的条目是一个数组(10,10),则可以将foreach循环的主体更改为以下代码:

If you do want the entry for EUR in the resulting array $C to be an array(10, 10) you can change the body of the foreach loop into the following code:

if (! isset($C[$key])) {
    $C[$key] = array();
}
$C[$key][] = $value;

编辑:

对于我的最后一句话和代码示例,您无需更改foreach的正文,只需执行以下操作:

For my last remark and code sample, instead of changing the body of the foreach you can simply do the following:

$C = array_merge_recursive($A, $B);

这篇关于数组合并和总计(如果相同)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆