PHP按日期排序数组? [英] PHP order array by date?

查看:32
本文介绍了PHP按日期排序数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
PHP 按包含日期的元素对多维数组进行排序

我在 PHP 数组中有一些来自 XML 或 JSON 的数据,如下所示:

I have some data from XML or JSON in a PHP array that looks like this:

[0]= array(2) {
    ["title"]= string(38) "Another title"
    ["date"]= string(31) "Fri, 17 Jun 2011 08:55:57 +0200"
}
[1]= array(2) {
    ["title"]= string(38) "My title"
    ["date"]= string(31) "Mon, 16 Jun 2010 06:55:57 +0200"
}

我想做的是按日期订购这两个项目.

  1. 当排序值在每个项目中时,是否可以按日期排序?
  2. 我需要将日期格式转换为时间戳吗?

我不想做的

我可以使用日期并将其设置为 ID,但这感觉不对,因为两个项目可以具有相同的日期,然后它就不会是唯一的.

I could use date and set it as the ID but that don't feel right, because two items can have the same date and then it would not be unique.

推荐答案

您不需要在排序之前将日期转换为时间戳,但这是一个好主意,因为如果没有这一步,排序将花费更多时间.

You don't need to convert your dates to timestamps before the sorting, but it's a good idea though because it will take more time to sort without this step.

$data = array(
    array(
        "title" => "Another title",
        "date"  => "Fri, 17 Jun 2011 08:55:57 +0200"
    ),
    array(
        "title" => "My title",
        "date"  => "Mon, 16 Jun 2010 06:55:57 +0200"
    )
);

function sortFunction( $a, $b ) {
    return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);

更新

在较新的 PHP 版本中,您也可以使用箭头函数.在这里你可以找到上面更简洁的版本:

Update

In newer PHP versions you can use arrow functions too. Here you can find a more concise version of the above:

usort($data, fn ($a, $b) => strtotime($a["date"]) - strtotime($b["date"]));

这篇关于PHP按日期排序数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆