如何获得最接近的日期与PHP中的日期数组相比较 [英] How to get closest date compared to an array of dates in PHP

查看:153
本文介绍了如何获得最接近的日期与PHP中的日期数组相比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章几乎对我回答了这个问题,但我有特定的需要,没有找到我在那里寻求的东西。这在我的经验之外;不能很好地包围我的头,所以我真正需要的是正确的方向。

This post almost answered this question for me, but I have a specific need and didn't find what I sought there. This lies right outside my experience; couldn't quite wrap my head around it, so all I really need is a point in the right direction.

让我们说一个数组如下:

Let's say I have an array as follows:

array(5) { 
    [0]=> "2013-02-18 05:14:54" 
    [1]=> "2013-02-12 01:44:03" 
    [2]=> "2013-02-05 16:25:07" 
    [3]=> "2013-01-29 02:00:15" 
    [4]=> "2013-01-27 18:33:45" 
}

我想有一种方法来提供一个日期(例如2013-02-04 14:11:16),并且有一个函数确定与数组最接近的匹配(这将是2013-02-05 16: 25:07在这种情况下)。

I would like to have a way to provide a date ("2013-02-04 14:11:16", for instance), and have a function determine the closest match to this in the array (which would be "2013-02-05 16:25:07" in this case).

感谢任何提示。谢谢! :

I'd appreciate any tips. Thanks! :)

推荐答案

我可能没有最好的命名约定,但是这里。

I may not have the best naming conventions, but here goes.

我计算日期数组和给定日期之间的间隔。我然后做一个排序,找到最小的差异。

I calculate the intervals between the array of dates and the given date. I then do a sort, to find the "smallest" difference.

$dates = array
(
    '0'=> "2013-02-18 05:14:54",
    '1'=> "2013-02-12 01:44:03",
    '2'=> "2013-02-05 16:25:07",
    '3'=> "2013-01-29 02:00:15",
    '4'=> "2013-01-27 18:33:45"
);


function find_closest($array, $date)
{
    //$count = 0;
    foreach($array as $day)
    {
        //$interval[$count] = abs(strtotime($date) - strtotime($day));
        $interval[] = abs(strtotime($date) - strtotime($day));
        //$count++;
    }

    asort($interval);
    $closest = key($interval);

    echo $array[$closest];
}

find_closest($dates, "2013-02-18 05:14:55");

这篇关于如何获得最接近的日期与PHP中的日期数组相比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆