asotahu
asotahu

Reputation: 55

how to merge array when the value is same

I have two arrays like this:

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 )
);

How to get output like this?

date 2014-03-15 = 3

date 2014-03-16 = 1

Upvotes: 0

Views: 42

Answers (1)

tesmojones
tesmojones

Reputation: 2667

You can not merge those array directly with array_merge, because the counting based on 'value', so you must create some codes, try this:

$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);

it will returns :

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

Upvotes: 2

Related Questions