5

嗨,我有 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

4 回答 4

2
$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) ;
于 2013-02-18T17:51:09.900 回答
0

试试这个

$count1 = array_count_values($array1);

$count1 = array_count_values($array2);

$count = $count1 + $count2;
于 2013-02-18T17:49:31.230 回答
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 以你指定的格式。我的假设是您的前 2 个数组称为 $array1 和 $array2。希望有帮助。

于 2013-02-18T17:51:04.537 回答
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'];

}
于 2013-02-18T17:51:54.863 回答