0

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.

Jorn Reed
  • 35
  • 5
  • It's unclear to me what your array looks like. Please provide a small example as PHP code so that your problem can be reproduced. – jspit Sep 20 '22 at 07:21
  • @jspit $sportivityClient = [ [ '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', ], ]; as you can see the second element, begins earlier. But I managed to fix it, apparently, a value returned false which made the sorting break – Jorn Reed Sep 21 '22 at 08:06
  • Your example data should already contain all relevant values and be added to your question. Here, for example, values with NULL. – jspit Sep 21 '22 at 08:35
  • Yeah it'll help! – Jorn Reed Sep 21 '22 at 09:09

1 Answers1

0

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'];
    });
Jorn Reed
  • 35
  • 5
  • Your solution is wrong. Make a test with the values 'StartTime' => '22/11/2022 10:30:00', and 'StartTime' => '20/12/2022 09:30:00'. – jspit Sep 21 '22 at 08:39
  • I don't see what is wrong, when I dump the data, everything is shown in the right order. – Jorn Reed Sep 21 '22 at 08:41
  • https://3v4l.org/8So1q A date in the format d/m/Y cannot be sorted as a string. – jspit Sep 21 '22 at 08:47