首页 > 解决方案 > 这是不是一个数组?

问题描述

我有这个数组填充了数据库中的数据

$collectTable1 = array( 'errand' => $interest->errand_id,
                        'timestamp' => $interest->timestamp,
                        'type' => $interest->type,
                        'amount' => $interest->amount
                    );

$collector[] = $collectTable1; 

我想对时间戳进行排序,就像这样

$sortTime = rsort($collectedData['timestamp']);

我试过了,我得到了这个输出

函数时间排序($a,$b){


 返回 (intval($a['timestamp']) > intval($b['timestamp']));
}

usort($collector, "timesort");

2017-12-01 10:53:26

我认为我会从下降的日期点得到?类似于 2018-09-04 12:32:16。

我的时间戳还包含 unixtimestamp 和常规日期,例如“2017-12-01 10:53:26”

标签: phparrayssortingusort

解决方案


我猜你在$collector.

如果你想对它们进行排序,timestamp你可以使用usort

考虑以下示例:

$collector = array();
$e1 = array("errand" => 1, "timestamp" => "2017-12-01 10:53:26");
$e2 = array("errand" => 2, "timestamp" => "2018-07-01 10:53:26");
$e3 = array("errand" => 3, "timestamp" => "2018-12-01 10:53:26");

$collector = array($e1, $e2, $e3);

function cmp($a, $b)
{
    return (strtotime($a['timestamp']) < strtotime($b['timestamp']));
}

usort($collector, "cmp");

当您的timestamp值在字符串中时,使用strtotime在比较之前将它们转换为 EPOC。

现在,$collector数组元素按timestamp值排序。

代码示例的输出是:

Array
(
    [0] => Array
        (
            [errand] => 3
            [timestamp] => 2018-12-01 10:53:26
        )
    [1] => Array
        (
            [errand] => 2
            [timestamp] => 2018-07-01 10:53:26
        )
    [2] => Array
        (
            [errand] => 1
            [timestamp] => 2017-12-01 10:53:26
        )
)

推荐阅读