嗨,我有两个像一样的数组
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" }
}
谢谢。
$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) ;
试试这个
$count1 = array_count_values($array1);
$count1 = array_count_values($array2);
$count = $count1 + $count2;
$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。希望能有所帮助。
//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'];
}