开发者

PHP find the nearest number

How can I find what table cell contains time that is nearest the current time?

The time table is created using PHP code like:

for ($i = 1; $i <= 24; $i++)
  {
  $timetable=strftime("%X开发者_如何学运维", mktime(0, 0, $hour[$i], $month, $day, $year));
  }

With this PHP code I get the time table for current day like:

   time   |
----------
 05:09:23 |
----------
 07:23:18 |
----------
 11:55:41 |
----------
 14:01:32 |
----------

The thing that I need is to change the background color of cell where the printed time is nearest the current time.

Hos can I do that?


Use this to do it:

$max = INF;
for ($i = 1; $i <= 24; $i++)
{
    $tabletime = mktime(0, 0, $hour[$i], $month, $day, $year);
    $timetable = strftime("%X", $tabletime);

    $diff = abs($tabletime - time());
    if($diff <= $max)
         $minID = $i;
}

Now $minID gives you the row that has lowest time difference.


Create two temporary variables. One of them will be the nearest cell index, the next will be the difference between the value of the cell index and the current time. (Oh, and store the current time as well. It will make things easier.)

$nearestTime = null;
$nearestDifference = INF; // infinite
$now = time();

Loop through your cells, and do the difference between their value and now. If it's smaller than $nearestDifference, the time is closer to now.

for ($i = 0; $i < count($cells); $i++)
{
    $time = strtotime($cells[i]); // or whatever is more appropriate for you
    $difference = abs($time - $now);
    if ($difference < $nearestDifference)
    {
        $nearestDifference = $difference;
        $nearestCell = $i;
    }
}

At the end of this, $nearestTime contains the index of the cell whose value is the nearest to now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜