如何在值相同时合并数组

时间:2014-05-03 01:50:30

标签: php arrays array-merge

我有两个这样的数组:

array1 = Array ( 
    [0] => Array ( [value] => 1 [date] => 2014-03-15 ),
    [1] => Array ( [value] => 1 [date] => 2014-03-15 )
);

array2 = Array ( 
    [0] => Array ( [value] => 1 [date] => 2014-03-15 ),
    [1] => Array ( [value] => 1 [date] => 2014-03-16 )
);

如何获得这样的输出?

  

日期2014-03-15 = 3

     

日期2014-03-16 = 1

1 个答案:

答案 0 :(得分:2)

你不能直接将这些数组与array_merge合并,因为计数基于'value',所以你必须创建一些代码,试试这个:

$array1 = array(
           array("value" => 1, "date" => "2014-03-15"),
           array("value" => 1, "date" => "2014-03-15"),
          );
$array2 = array(
           array("value" => 1, "date" => "2014-03-15"),
           array("value" => 1, "date" => "2014-03-16"),
          );

foreach(array_merge($array1, $array2) as $arr){
   !isset($array[$arr['date']]) ?  $array[$arr['date']] = $arr['value'] :  $array[$arr['date']] += $arr['value'];
}

print_r($array);

它会返回:

Array ( [2014-03-15] => 3 [2014-03-16] => 1 )