There are 2 arrays.

The first - shows by date

[0] => Array ( [date] => 20170224 [total_views] => 41 ) [1] => Array ( [date] => 20170225 [total_views] => 7 ) [2] => Array ( [date] => 20170226 [total_views] => 750 ) [3] => Array ( [date] => 20170227 [total_views] => 50 ) 

Second - clicks on dates

 [0] => Array ( [date] => 20170224 [total_clicks] => 418 ) [1] => Array ( [date] => 20170225 [total_clicks] => 72 ) [2] => Array ( [date] => 20170226 [total_clicks] => 50 ) 

As you can see, some dates in 2 arrays do not match. Yes, and arrays themselves may differ in the number of elements. It is necessary to integrate these 2 arrays into one. And where there is no data put 0.

It should be such an array.

 [0] => Array ( [date] => 20170224 [total_views] => 41 [total_clicks] => 418 ) [1] => Array ( [date] => 20170225 [total_views] => 7 [total_clicks] => 72 ) [2] => Array ( [date] => 20170226 [total_views] => 750 [total_clicks] => 50 ) [3] => Array ( [date] => 20170227 [total_views] => 50 [total_clicks] => 0 ) 

As you can see, there are no clicks for 20170227 - it costs 0. But maybe in reverse, there are clicks, but there are no impressions.

  • Another clarification. Both arrays can be of different lengths. For example, in the first array there can be 10 dates (elements) and in the second one a date (element). And the worst thing is that one of the arrays may not exist at all! In general, the problem is not simple. - Deniel

3 answers 3

Build an index first, by date:

 $res = []; foreach ($arr1 as $row) { $row['total_clicks'] = 0; $res[$row['date']] = $row; } 

Then add clicks from the second array:

 foreach($arr2 as $row) { if (isset($res[$row['date']])) { $res[$row['date']]['total_clicks'] = $row['total_clicks']; } else { $row['total_views'] = 0; $res[$row['date']] = $row; } } 

If you do not need dates in the keys - reset:

 $res = array_values($res); 

    I wrote on the move, I hope, was not mistaken

      $array3 = array(); $i=0; foreach($array1 as $v1){ $array3[$i]['date'] = $v['date']; $array3[$i]['total_views'] = $v['total_views']; $array3[$i]['total_clicks'] = 0; $i++; } foreach($array2 as $v2){ $f = false; foreach($array3 as $v3){ if($v3['date'] == $v2['date']) { $v3['total_clicks']=$v2['total_clicks']; $f = true; } } if(!$f) $array3[]=array('date'=>$v2['date'],'total_clicks'=>$v2['total_clicks'],'total_views'=>0); } 
       $arrayFix = array(); for($i=0; $i<count($arrayFirst); $i++){ $arrayFix[] = array( "date" => $arrayFirst[$i]["date"], "total_views" => $arrayFirst[$i]["total_views"], "total_clicks" => "0" ); } for($i=0; $i<count($arrayFix); $i++){ $date_view = $arrayFix[$i]["date"]; for($j=0; $j<count($arrayFix); $j++){ if($date_view==$arraySecont[$j]["date"]){ $arrayFix[$j]["total_clicks"] = $arraySecont[$j]["total_clicks"]; } } } print_r($arrayFix);