Amitesh Kumar Amitesh Kumar - 2 months ago 10
PHP Question

Compare two array And Store in another array with matched and unmatched as 0

I found some solutions on google but they are not fulfilling my requirement.
I have an array,

$current_week = self::CurrentWeekDateRange($s_date, $e_date);


it is giving me result:

[0] => 2016-09-06
[1] => 2016-09-07
[2] => 2016-09-08
[3] => 2016-09-09
[4] => 2016-09-10
[5] => 2016-09-11
[6] => 2016-09-12
[7] => 2016-09-13
[8] => 2016-09-14
[9] => 2016-09-15
[10] => 2016-09-16
[11] => 2016-09-17
[12] => 2016-09-18


now My Next array is like this: user log $return a array

[0] => Array
(
[date_log] => 2016-09-08
[total] => 15
)

[1] => Array
(
[date_log] => 2016-09-13
[total] => 30
)

[2] => Array
(
[date_log] => 2016-09-14
[total] => 400
)


No i have , 3 user means it print 3 times user log.
So what i want is i want to match date_log to above my first array,

If its matches it will give it will get store in another array and if not match then it will store 0.

My problem i am using two loops ant it is printing loop1 * loop2 times value but i want only $current_week times values


I tried like this:

$current_week = self::CurrentWeekDateRange($s_date, $e_date);

$i = 0;

foreach ($current_week as $day){
foreach ($returns as $return) {
if($day == $return['date_log']){
$array_total_hours[$i]['total'] = $return['total'];
$array_total_hours[$i]['date_log'] = $return['date_log'];
}
else {
$array_total_hours[$i]['date_log'] = $return['date_log'];
$array_total_hours[$i]['total'] = 0;
}

$i++;
}
}

print( $array_total_hours);


I want my result like this:

[2016-09-06] => Array
(
[date_log] => 2016-09-06
[total] => 0
)

[2016-09-07] => Array
(
[date_log] => 2016-09-07
[total] => 30
)

[2016-09-08] => Array
(
[date_log] => 2016-09-08
[total] => 400
)
[2016-09-09] => Array
(
[date_log] => 2016-09-09
[total] => 0
)
.
.
.
.
.
.
.
[2016-09-18] => Array
(
[date_log] => 2016-09-18
[total] => 0
)

Answer

This one should do the job.

$current_week = self::CurrentWeekDateRange($s_date, $e_date); 

$finalResult = array();
foreach ($current_week as $date) {
    $finalResult[$date] = array('date_log' => $date, 'total' => 0);
}

$dates = array_keys($finalResult);
// not sure where this one comes from
$nextArray = array(
     array('date_log' => '2016-09-08', 'total' => 15),
     array('date_log' => '2016-09-13', 'total' => 30)
     );

foreach ($nextArray as $return) {
    $record = array('date' => '', 'total' => 0);
    if (in_array($return['date'], $dates)) {
        $finalResult[$return['date']]['total'] = $return['total'];
    }
}