phparrayssortingdatemultidimensional-array

Sort a 2d array by a datetime column formatted as d.m.Y H:i


I'm confused - I'm not able to find the bug in this code snippet.

I want to order the dates inside this array by date - starting by the next date.

<?php

$data = [
  [
    "id" => "3f57dc7c-a698-e911-a95e-000d3a454330",
    "date" => [
        [
        "start_date" => "23.11.2020 07:00",
        "end_date" => "04.12.2020 16:00"
      ],
      [
        "start_date" => "02.03.2020 07:00",
        "end_date" => "13.03.2020 16:00"
      ],
      [
        "start_date" => "06.01.2020 07:00",
        "end_date" => "14.02.2020 21:00"
      ],
      [
        "start_date" => "20.01.2020 07:00",
        "end_date" => "28.02.2020 07:00"
      ],
      [
        "start_date" => "23.03.2020 07:00",
        "end_date" => "03.04.2020 15:00"
      ],
      [
        "start_date" => "31.08.2020 06:00",
        "end_date" => "09.10.2020 15:00"
      ],
      [
        "start_date" => "12.10.2020 06:00",
        "end_date" => "23.10.2020 15:00"
      ]
    ]
  ]
];

foreach ($data as $entry) {
    usort($entry['date'], function($a, $b) {
        $a = DateTime::createFromFormat('d.m.Y H:i', $a['start_date']);
        $b = DateTime::createFromFormat('d.m.Y H:i', $b['start_date']);
        return $a <=> $b;
    });
}

var_dump($data[0]['date']);

online playground: https://3v4l.org/39k53


Solution

  • You can use References in this case https://www.php.net/manual/en/language.references.whatdo.php

    foreach ($data as &$entry) {
        usort($entry['date'], function($a, $b) {
            $a = DateTime::createFromFormat('d.m.Y H:i', $a['start_date']);
            $b = DateTime::createFromFormat('d.m.Y H:i', $b['start_date']);
            return $a <=> $b;
        });
    }