Nisham Mahsin
Nisham Mahsin

Reputation: 1399

Add array items based on a value and remove duplicate value in php

I have an array in php like this

Array ( 
    [0] => Array ( 
             [date] => 21/06/2014 
             [total_booking] => 1 
           ) 
    [1] => Array ( 
             [date] => 21/06/2014 
             [total_booking] => 1 
           ) 
    [2] => Array ( 
             [date] => 22/06/2014 
             [total_booking] => 2 
           )
)

What i am trying to do is i want to remove duplicate dates and add total_booking of removed date to one unique date. Eg:

I have 1 booking in an instance and 2 bookings in other instance on 21/06/2014. Now I want to add all bookings, in this case 3 on 21/06/2014.

Following is my code:

$booking_total=0;

$trend_array=array();
$do_not_duplicate=array();
foreach($EM_Bookings as $EM_Booking){
    $booking_date = date_i18n(get_option('dbem_date_format'), $EM_Booking->timestamp);
    $booking_total  = $EM_Booking->get_spaces();
    $do_not_duplicate[]=$booking_date;
    if (in_array($booking_date, $do_not_duplicate)) {
        $do_not_duplicate[]=$booking_date;
        $booking_array=array('date' =>$booking_date,'total_booking'=>$booking_total);
        array_push($trend_array,$booking_array);
    }else{
        // i want to add  $booking_total  to corresponding date
    }

}

Upvotes: 2

Views: 107

Answers (3)

Alex
Alex

Reputation: 1573

$unique = array();
foreach($EM_Bookings as $booking){
    $date = $booking['date'];
    if(!key_exists($date, $unique)){
            $unique[$date] = $booking['total_booking'];
    }else{  
            $unique[$date] += $booking['total_booking'];
    }
}

/*
 print_r($unique); 

 Array
(
[21/06/2014] => 2
[22/06/2014] => 2
)

*/

Upvotes: 1

Holt
Holt

Reputation: 37626

I would create a new array indexed with date, and then recreate your array:

$newarray = array () ;
foreach ($EM_Bookings as $EM_Booking) {
    $booking_date = date_i18n(get_option('dbem_date_format'), $EM_Booking->timestamp);
    $booking_total  = $EM_Booking->get_spaces();
    if (array_key_exists($booking_date, $newarray)) {
        $newarray[$booking_date] += $booking_total ; // Add to existing array
    }
    else {
        $newarray[$booking_date] = $booking_total ; // Create new
    }
}

Here, newarray looks like:

Array (
    [21/06/2014] => 2,
    [22/06/2014] => 2
) 

So you can easily create the array you want, like so:

$finalarray = array () ;
foreach ($newarray as $date => $booking) {
    $finalarray[] = array(
        'date' => $date,
        'total_booking' => $booking
    ) ;
}

Upvotes: 1

Lars Ebert-Harlaar
Lars Ebert-Harlaar

Reputation: 3537

Basically, you want the number of bookings per day, no?

$data = array([...]);

$days = array();

foreach($data as $day => $num) {
    if(!isset($days[$day])) {
        $days[$day] = 0;
    }

    $days[$day] += $num;
}

Is this what you want?

Upvotes: 1

Related Questions