【发布时间】:2016-01-04 22:55:13
【问题描述】:
我使用这个php函数将数字时间戳转换为“7天前”之类的东西,但是某个时间戳返回division by zero错误,我不知道如何修复该函数。
function timestamp_to_ago($timestamp){
if(isset($timestamp) and $timestamp !=''){
$difference = time() - $timestamp;
$periods = array("second", "minute", "hour", "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]; // <<< line with problem
}
$difference = round($difference);
if($difference != 1) $periods[$j].= "s";
$text = "$difference $periods[$j] ago";
return $text;
}
}
// returns division by zero error
echo timestamp_to_ago(1135288800);
// doesn't return division by zero
echo timestamp_to_ago(1235288800);
除以零在$difference /= $lengths[$j];这一行触发,但我不知道如何修复该函数以避免此错误。
【问题讨论】:
-
如果 $lengths[$j]==0 { $lengths[$j]=1}
-
也许您可以检查
$lengths[$j]值并仅在它具有非零值时执行除法运算?
标签: php function divide-by-zero