具有相同键的2个数组元素的总和

时间:2013-02-18 17:46:23

标签: php arrays multidimensional-array sum

嗨我有2个阵列,比如

 array(a) {  [0]=> array(2) { ["count"]=> string(2) "22" ["hour"]=> string(1) "0" }
             [1]=> array(2) { ["count"]=> string(2) "17" ["hour"]=> string(1) "1" } 
             [2]=> array(2) { ["count"]=> string(2) "22" ["hour"]=> string(1) "2" } 
             [3]=> array(2) { ["count"]=> string(2) "15" ["hour"]=> string(1) "3" } 
             [4]=> array(2) { ["count"]=> string(2) "15" ["hour"]=> string(1) "4" }
            }

我的第二个数组有不同的(计数)值

 array(b) {  [0]=> array(2) { ["count"]=> string(2) "12" ["hour"]=> string(1) "0" }
             [1]=> array(2) { ["count"]=> string(2) "36" ["hour"]=> string(1) "1" } 
             [2]=> array(2) { ["count"]=> string(2) "59" ["hour"]=> string(1) "2" } 
             [3]=> array(2) { ["count"]=> string(2) "5"  ["hour"]=> string(1) "3" } 
             [4]=> array(2) { ["count"]=> string(2) "27" ["hour"]=> string(1) "4" }
            }

请告诉我如何获得两个数组的[“count”]之和并得到一个新的数组

 array(c) {  [0]=> array(2) { ["count"]=> string(2) "34" ["hour"]=> string(1) "0" }
             [1]=> array(2) { ["count"]=> string(2) "53" ["hour"]=> string(1) "1" } 
             [2]=> array(2) { ["count"]=> string(2) "81" ["hour"]=> string(1) "2" } 
             [3]=> array(2) { ["count"]=> string(2) "20"  ["hour"]=> string(1) "3" } 
             [4]=> array(2) { ["count"]=> string(2) "42" ["hour"]=> string(1) "4" }
            }

谢谢。

4 个答案:

答案 0 :(得分:1)

$result_array = array() ;

for ($i = 0, $length = count($a_array) ; $i < $length ; $i++){
  $result_array[$i] = $a_array[$i] ;
  $result_array[$i]["count"] += $b_array[$i]['count'] ;  
}

var_dump($result_array) ;

答案 1 :(得分:0)

试试这个

$count1 = array_count_values($array1);

$count1 = array_count_values($array2);

$count = $count1 + $count2;

答案 2 :(得分:0)

$sum = array();
foreach($array1 as $k=>$v) {
  foreach($array2 as $k1=>$v1) {
    if($v['hour'] == $v1['hour']) {
      $sum[] = array('count'=> ($v['count'] == $v1['count']), 'hour' => $v['hour']);
    }
  }
}

应该以指定的格式为您提供一个新数组$ sum。我的假设是你的前两个数组被称为$ array1和$ array2。希望有所帮助。

答案 3 :(得分:0)

//new array to hold answers
$array_results=array();

//loop through first array
foreach ($array_first as $key=>$v){

//use key of current element to get corresponding value from second array
//add them together and add into combined array
$array_results[]=$v['count']+$array_second[$key]['count'];

}