Home > other >  Filtering array by date
Filtering array by date

Time:09-22

I have an array filled with items. Every item has a StartDate with the format d/m/Y H:i:s.

I want to order the array items, from earliest to last.

I already tried doing

$client = [ [ 'LessonId' => 1, 'StartTime' => '20/11/2022 10:30:00', 'EndTime' => '20/11/2022 11:30:00', 'LessonName' => 'Dance', ], [ 'LessonId' => 2, 'StartTime' => '20/11/2022 09:30:00', 'EndTime' => '20/11/2022 10:30:00', 'LessonName' => 'Dance', ], ];

usort($client, function ($a, $b) {
    $pos_a = strtotime(\DateTime::createFromFormat('d/m/Y H:i:s', $a['StartTime']));
    $pos_b = strtotime(\DateTime::createFromFormat('d/m/Y H:i:s', $b['StartTime']));
    return $pos_a <=> $pos_b;
});

Sadly it's not working since the array is still in it's old order. I'm not even sure if I still need strtotime() since I already tell php which date format the fields are.

CodePudding user response:

At first it didn't work because one or more values returned false. Later after figuring that out, I managed to fix it by converting the dates to a time stamp. and doing:

usort($arrayToSort , function ($a, $b) {
        if($a['startTime'] == null && $b['startTime'] == null) return 0;
        if($a['startTime'] == null) return 1; //1 -> "a is greater than b"
        if($b['startTime'] == null) return -1; //-1 -> "a is less than b"
        
        return $a['startTime'] <=> $b['startTime'];
    });
  • Related