【问题标题】:How to return the timestamps from an indexed array of timestamps with the earliest and latest clock time?如何从具有最早和最新时钟时间的时间戳索引数组中返回时间戳?
【发布时间】:2021-12-24 00:58:40
【问题描述】:

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

$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'));
}

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

我的做法:

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));
}

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

如何返回时钟时间最早和最晚的原始时间戳?

【问题讨论】:

    标签: php arrays time max min


    【解决方案1】:

    你可以使用下一个代码:

    //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
            )
    
    )
    

    【讨论】:

    • 你能详细解释一下你的代码吗? array_map() 也可以吗?
    • 当然,添加了 cmets
    • 谢谢! array_map() 也可以吗?
    • 可能是。不确定。 array_map 函数用于更改给定数组的每个元素,但 array_reduce - 将数组缩减为针值
    • 使用array_map:phpize.online/…
    猜你喜欢
    • 2020-09-28
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多