php PHP按日期值对数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15557373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:28:17  来源:igfitidea点击:

PHP Sort Array by date value

phparraysdatesorting

提问by Dave

I have the following array format in my php code:

我的 php 代码中有以下数组格式:

foreach ($events as $info) {
    $events_array[] = array(
        'title' => $info->Name,
        'date'  => $info->Date
    );
}
function cb($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
}
usort($events_array, 'cb');

Edit: The date values are in the format: YYYY-MM-DD

编辑:日期值的格式为:YYYY-MM-DD

Actually, when I do print_r, I get

实际上,当我执行 print_r 时,我得到

[title] => SimpleXMLElement Object ( ) [date] => SimpleXMLElement Object ( )

回答by silkfire

You have to create your own multi column sort function (because your array is 2-dimensional):

您必须创建自己的多列排序函数(因为您的数组是二维的):

array_sort_by_column($events_array, 'date');

var_dump($events_array);

The sorting function:

排序功能:

function array_sort_by_column(&$array, $column, $direction = SORT_ASC) {
    $reference_array = array();

    foreach($array as $key => $row) {
        $reference_array[$key] = $row[$column];
    }

    array_multisort($reference_array, $direction, $array);
}

回答by Miles M.

You can use USortphp function.

您可以使用USortphp 功能。

Give a look at this thread:

看看这个线程:

PHP Sort a multidimensional array by element containing date

PHP按包含日期的元素对多维数组进行排序