按格式为 d.m.Y H:i [重复] 的日期时间列对二维数组进行排序

问题描述 投票:0回答:2

我很困惑 - 我无法找到此代码片段中的错误。

我想按日期对这个数组中的日期进行排序 - 从下一个日期开始。

<?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']);

在线游乐场:https://3v4l.org/39k53

php arrays sorting date multidimensional-array
2个回答
3
投票

在这种情况下您可以使用参考文献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;
    });
}

0
投票

我认为这是因为你正在排序

$entry['date']
,这是循环内的临时变量。排序不会更新父对象中数组的副本。

尝试这样,直接访问数组:

usort($data[0]['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);

或者,您可以坚持原来的方法(预期顶级数组中的多个条目),但输出循环中出现的每个

$entry
实例的内容,而不是父级 - 它将被排序:

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($entry['date']);
}
© www.soinside.com 2019 - 2024. All rights reserved.