首页 新闻 会员 周边 捐助

php 两个数组,若键相同,则值合并

0
[待解决问题]

将下列两个数组:
$arr1 = array('9' => '4.08', '10' => '0.10', '11' => '4.08', '12' => '0.01');
$arr2 = array('8' => '0.01', '10' => '0.01', '11' => '0.01');
合并成如下格式:
$arr3 = array('8' => '0.01', '9' => '4.08', '10' => '0.11', '11' => '4.09', '12' => '0.01');
即,键相同则值相加,并原样保留无相同键值对。

王水饺的技术栈的主页 王水饺的技术栈 | 初学一级 | 园豆:7
提问于:2019-03-03 01:10
< >
分享
所有回答(2)
0

看下能用吗:

<!DOCTYPE html>
<html>
  <body>

    <?php
    $arr1 = array('9' => '4.08', '10' => '0.10', '11' => '4.08', '12' => '0.01');
    $arr2 = array('8' => '0.01', '10' => '0.01', '11' => '0.01');
    $arr3 = $arr1;//把数组1赋值给新的数组3

    foreach($arr2 as $x=>$x_value)//遍历数组2
    {
    if (array_key_exists($x, $arr3)) {//如果存在key,则值相加
    $arr3[$x] += $arr2[$x];
    }
    else {//不存在key,则新增
    $arr3[$x] = $x_value;
    }
    }
    ksort($arr3);//根据key进行升序排列

    foreach($arr3 as $x=>$x_value)
    {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
    }
    ?>

  </body>
</html>
三人乐乐 | 园豆:4823 (老鸟四级) | 2019-03-04 13:47
0

$arr1 = array('9' => '4.08', '10' => '0.10', '11' => '4.08', '12' => '0.01');
$arr2 = array('8' => '0.01', '10' => '0.01', '11' => '0.01');
$arr = [];

    foreach ($arr1 as $key => $value) {
        if(isset($arr[$key])){
            $arr[$key] += $value;
        }else{
            $arr[$key] = $value;
        }
    }

    foreach ($arr2 as $key => $value) {
        if(isset($arr[$key])){
            $arr[$key] += $value;
        }else{
            $arr[$key] = $value;
        }
    }  

    ksort($arr);
火山田 | 园豆:202 (菜鸟二级) | 2019-04-09 15:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册