按日期对数组排序

时间:2019-03-27 16:15:18

标签: php arrays sorting

我的数组为每个字段(例如,日期,名称等)都有一个数组。如何按日期对数组排序?我应该创建另一个数组吗?我可以在这里使用排序还是不排序。如果是,怎么办?这是我的数组:

Array
(
    [date] => Array
        (
            [0] => 03/11/2019
            [1] => 03/19/2019
            [2] => 03/15/2019
            [3] => 12/15/2018
        )

    [name] => Array
        (
            [0] => Lowa
            [1] => Stephanie
            [2] => Allan
            [3] => Joffer
        )

    [number] => Array
        (
            [0] => 178989898
            [1] => 111111111
            [2] => 222222222
            [3] => 333333333
        )

    [unit] => Array
        (
            [0] => HR
            [1] => VPP
            [2] => 
            [3] => OAT
        )

    [department] => Array
        (
            [0] => Chemistry
            [1] => IT
            [2] => Lab
            [3] => Contractor
        )

) 

最后,我的第一个元素是: 03/19/2019 Stephanie 111111111 VPP IT

2 个答案:

答案 0 :(得分:1)

首先保存数组的键-然后使用array_value转换为整数键,以便可以使用...运算符。

然后,您可以将array_filternull函数一起使用来重新组织数组。下一步将使用array_maparray_combine找回密钥。

最后一步-用usort按“数据”排序

考虑以下示例:

$arr = ["date" => ["3", "7", "5"], "name" => ["aa", "bb", "cc"]]; // this can have a lot more sub-array inside
$keys = array_keys($arr); // extract the keys for later use
$res = array_map(null, ...array_values($arr)); // transposed the array
$res = array_map(function ($e) use ($keys) {return array_combine($keys, $e);}, $res); // return the keys to the transposed array
usort($res, function ($a, $b) {return strcmp($a['date'], $b['date']);} ); // sort all by "date"

参考:

array-keysarray-filterarray-mapusortarray-values

通知 @MarcoS发表有关比较日期的评论

答案 1 :(得分:1)

我认为您的数据可以得到更好的组织:

$newArr = Array
(
    [0] => Array
        (
            [date] => 03/11/2019
            [name] => Lowa
            [number] => 178989898
            [unit] => HR
            [department] => Chemistry
        )

    [1] => Array
        (
            [date] => 03/19/2019
            [name] => Stephanie
            [number] => 111111111
            [unit] => VPP
            [department] => IT
        )

    [2] => Array
        (
            [date] => 03/15/2019
            [name] => Allan
            [number] => 222222222
            [unit] =>
            [department] => Lab
        )

    [3] => Array
        (
            [date] => 12/15/2018
            [name] => Joffer
            [number] => 333333333
            [unit] => OAT
            [department] => Contractor
        )
);

然后,您可以简单地按以下顺序对其进行排序:

function cmp($a, $b) {
  if ($a["date"] == $b["date"]) return 0;
  return ($a["date"] < $b["date"]) ? -1 : 1;
}

usort($newArr, "cmp");

请注意,日期格式为“月/日/年”,不能按字母顺序排序。
您绝对应该为日期使用年/月/日格式,或者编写更具体的cmp()函数...

更新:要在评论中回答OP的问题:只需颠倒$ row和“ field”顺序:

for ($row = 0; $row < count($date); $row++) {
  $newArr[$row]['date'] = $date[$row];
  $newArr[$row]['name'] = $name[$row];
  ...
}