如何 return 从具有最早和最晚时钟时间的时间戳索引数组中提取时间戳?

How to return the timestamps from an indexed array of timestamps with the earliest and latest clock time?

有一个带有时间戳的大数组,例如:

$timestamps = array();
for ($i = 0; $i < 5000; $i++) {
    $timestamps[] = mt_rand(strtotime('1900-01-01 00:00:00 am'), strtotime('2100-12-31 11:59:59 pm'));
}

现在我需要 return 具有最早(最小)和最晚(最大)时钟时间的时间戳。

我的做法:

echo date('Y-m-d h:i:s a', min(array_map('callback', $timestamps)));
echo "\n";
echo date('Y-m-d h:i:s a', max(array_map('callback', $timestamps)));

function callback($timestamp) {
    return strtotime(date('h:i:s a', $timestamp));
}

这实际上提供了最早和最晚的时钟时间,当然还有当前日期(今天)。

如何return原始时间戳与最早和最晚的时钟时间?

您可以使用下一个代码:

//run array_reduce over array
$res = array_reduce(
    $timestamps, // timestaps array
    function($res, $t) {
        // get time from timestamp
        $time = date('H:i:s', $t);

        // if result min not exists
        // or more then $time store new value to $res['min']
        if (is_null($res['min'][0]) || $time<$res['min'][0])
            $res['min'] = [$time, date('Y-m-d h:i:s a', $t)];


        // if result max not exists
        // or less then $time store new value to $res['max']
        if (is_null($res['max'][0]) || $time>$res['max'][0])
            $res['max'] = [$time, date('Y-m-d h:i:s a', $t)];

        // return updated result
        return $res;
    },
    // define initial $res with null values
    ['min'=>[null, null], 'max'=>[null, null]]
);

Share PHP online

结果:

Array
(
    [min] => Array
        (
            [0] => 00:00:30
            [1] => 1997-05-03 12:00:30 am
        )

    [max] => Array
        (
            [0] => 23:59:36
            [1] => 1983-07-21 11:59:36 pm
        )

)