按时间戳对 PHP 进行数组排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5949179/
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 23:00:03  来源:igfitidea点击:

Array Sorting PHP by timestamp

phparrayssorting

提问by Mr.Boon

I have problem ordering an array in the way I want.

我在按我想要的方式订购数组时遇到问题。

This is an example output of my array: http://pastebin.com/GJNBmqL7

这是我的阵列的示例输出:http: //pastebin.com/GJNBmqL7

Data comes from various database at once, so I'm limited in the way that I put the data into the array.

数据同时来自各种数据库,因此我将数据放入数组的方式受到限制。

The [2] always contains a linux timestamp. Now I want the entire array to be ordered by that timestamp, with the lowest value first.

[2] 总是包含一个 linux 时间戳。现在我希望整个数组按该时间戳排序,最低值在前。

How can I get that done?

我怎样才能做到这一点?

采纳答案by mjspier

here an array_multisortexample:

这里是一个array_multisort示例:

foreach ($array as $key => $node) {
   $timestamps[$key]    = $node[2];
}
array_multisort($timestamps, SORT_ASC, $array);

回答by Headshota

use usort that accepts custom function to sort arrays:

使用接受自定义函数的 usort 对数组进行排序:

usort

排序

your function may look something like:

您的函数可能类似于:

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

回答by Coin_op

You can do this simply by using a custom sort. So assuming your datestamp is always index 2:

您只需使用自定义排序即可完成此操作。因此,假设您的日期戳始终为索引 2:

function sortArray($a1, $a2){
    if ($a1[2] == $a2[2]) return 0;
    return ($a1[2] > $a2[2]) ? -1 : 1;
}

usort($array, "sortArray");

回答by Emil Vikstr?m

usortis the easiest to work with, but you can also check out array_multisort.

usort是最容易使用的,但您也可以查看array_multisort

回答by Davinder Snehi

This can be achieved with following code.

这可以通过以下代码实现。

usort($variable, function ($a, $b) {
 if ($a['timestamp'] == $b['timestamp']) {
    return 0;
}
return ($a['timestamp'] < $b['timestamp']) ? 1 : -1;

});

});

This will result in sorted array of $variable, assuming time-stamp is at $variable[0]['timestamp']; $variable[0]['timestamp']; and so on.

这将导致 $variable 的排序数组,假设时间戳在 $variable[0]['timestamp']; $variable[0]['timestamp']; 等等。

回答by Joshua - Pendo

Use usort and create your own function, http://php.net/manual/en/function.usort.php

使用usort并创建自己的函数,http://php.net/manual/en/function.usort.php

回答by hsz

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

$data = array( /* your data */ );

usort($data, "cmp");

回答by Abel Mohler

It might be easier to insert the data into a single temporary table, then SELECT it, with ORDER BY timestamp

将数据插入到单个临时表中,然后使用 ORDER BY 时间戳选择它可能更容易