dongyili5843
dongyili5843
2011-01-25 21:26

php数学加法2个关联数组中的数值

已采纳

Probably a simple one for you :

I have 2 arrays

$array1 = array(
  'foo' => 5,
  'bar' => 10,
  'baz' => 6
);

$array2 = array(
  'x' => 100,
  'y' => 200,
  'baz' => 30
);

I wish to get a third array by combining both the above, which should be :

$result_array = array(
  'foo' => 5,
  'bar' => 10,
  'baz' => 36,
  'x' => 100,
  'y' => 200,
);

Is there any built in 'array - way' to do this, or will I have to write my own function ? Thanks

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongliu8559 dongliu8559 10年前
    $resultArray = $array1;
    foreach($array2 as $key => $value) {
       if (isset($resultArray[$key])) {
          $resultArray[$key] += $value;
       } else {
          $resultArray[$key] = $value;
       }
    }
    
    点赞 评论 复制链接分享
  • douchai7891 douchai7891 10年前

    There's no built-in function for this, you'll have to write your own.

    点赞 评论 复制链接分享
  • dtkwt62022 dtkwt62022 10年前

    you need

    $newArray = $array1;
    foreach($array2 as $key => $value) {
        if(array_key_exists($key, $newArray)){
         $newArray[$key] += $value;
        }else{
         $newArray[$key] = $value;
        }
    }
    
    点赞 评论 复制链接分享

相关推荐