-1

知道为什么这个 php 函数会导致我的网站冻结吗?

 function makeAgo($timestamp){

  $difference = time() - $timestamp;
  $periods = array("sec", "min", "hr", "day", "week", "month", "year", "decade");
  $lengths = array("60","60","24","7","4.35","12","10");
  for($j = 0; $difference >= $lengths[$j]; $j++)
    $difference /= $lengths[$j];
    $difference = round($difference);
  if($difference != 1) $periods[$j].= "s";
    $text = "$difference $periods[$j] ago";
    return $text;
}
4

2 回答 2

0

我想您将需要更改为:

  for($j = 0; $difference >= $lengths[$j]; $j++){
    $difference /= $lengths[$j];
    $difference = round($difference);
    if($difference != 1) $periods[$j].= "s";
      $text = "$difference $periods[$j] ago";
      return $text;
  }

因为如果使用不带大括号的循环,则只有第一个 next 语句会在循环中连续执行,而不会执行任何其他语句。

于 2013-05-08T05:06:50.737 回答
0
  1. 如果您的时间戳差异小于零值,您的函数就会冻结。

  2. 还有一件事你忘了提到十年或一年的长度。否则你的功能工作超级......!

试试下面..!!

 function makeAgo($timestamp){

$difference = time() - $timestamp;
if($difference < 0)
{
  $difference = 0;
}
$periods = array("sec", "min", "hr", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10","10");
for($j = 0; $difference >= $lengths[$j]; $j++)
  $difference /= $lengths[$j];
  $difference = round($difference);
if($difference != 1) $periods[$j].= "s";
  $text = "$difference $periods[$j] ago";
  return $text;
}
于 2013-05-08T05:20:55.190 回答