Nisham Mahsin
Nisham Mahsin

Reputation: 1399

Remove dates from array other than between FROM DATE and TO DATE

I have an array in php like this

Array ( 
    [0] => Array ( 
             [date] => 21/07/2014 
             [total_booking] => 1 
           ) 
    [1] => Array ( 
             [date] => 1/08/2014 
             [total_booking] => 1 
           ) 
    [2] => Array ( 
             [date] => 2/09/2014 
             [total_booking] => 2 
           )
)

if i get value $_POST['from_date'] and $_POST['to_date'] all array other than between this from_date,to_date should be removed.

Edit my code

foreach ($newarray as $newarray){
if ($newarray[Date] < $to_date && $from_date > $newarray[Date])
{
 // i want to remove this row from array
}

}

Upvotes: 0

Views: 864

Answers (1)

Dave Chen
Dave Chen

Reputation: 10975

Here's a solution using array_filter:

<?php

$data = array(
    array(
        'date' => '21/07/2014',
        'total_booking' => '1'
    ),
    array(
        'date' => '1/08/2014',
        'total_booking' => '1'
    ),
    array(
        'date' => '2/09/2014',
        'total_booking' => '2'
    )
);

$from_date = strtotime('01-08-2014'); //$_POST['from_date']
$to_date = strtotime('21-08-2014'); //$_POST['to_date']

$data = array_filter($data, function($array) use ($from_date, $to_date) {
    $epoch = strtotime(str_replace('/', '-', $array['date']));
    return $epoch >= $from_date && $epoch <= $to_date;
});

$data = array_values($data);

print_r($data);

Output:

Array
(
    [0] => Array
        (
            [date] => 1/08/2014
            [total_booking] => 1
        )

)

Only one element is outputted because only 1/08/2014 is between 1/08/2014 and 21/08/2014.

For earlier PHP versions:

function filter($array) {
    $from_date = strtotime('01-08-2014'); //$_POST['from_date']
    $to_date = strtotime('21-08-2014'); //$_POST['to_date']

    $epoch = strtotime(str_replace('/', '-', $array['date']));
    return $epoch >= $from_date && $epoch <= $to_date;
}

$data = array_filter($data, 'filter');

Upvotes: 2

Related Questions