如何从此函数中删除除零?

时间:2016-01-04 22:55:13

标签: php function divide-by-zero

我使用这个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];处触发除零,但我不知道如何修复该函数以避免此错误。

3 个答案:

答案 0 :(得分:3)

如果它已经超过十年了会发生什么?

    for($j = 0; isset($lengths[$j]) && $difference >= $lengths[$j]; $j++){
        $difference /= $lengths[$j]; // <<< line with problem
    }

答案 1 :(得分:1)

问题是当你的循环到达$lengths的末尾时它不会停止。当$i达到数组的长度时,$lengths[$i]未定义,并且在分割时会转换为0

您可以使用foreach代替for

foreach ($lengths as $j => $length) {
    if ($difference < $length) {
        break;
    }
    $difference /= $length;
}
$period = $periods[$j];

答案 2 :(得分:0)

似乎这些数组是静态的并为您的结果建立基线。如果是这样,您错过了"second"的值。您需要在lengths中添加值或从"seconds"中删除periods以修正此除以零的错误。我相信(在阅读了你的问题之后,下面是你想要实现的目标,因为它看起来逻辑是有缺陷的。

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 = 1; $difference >= $lengths[$j-1]; $j++){
            $difference /= $lengths[$j];
        }
        $difference = round($difference);
        if($difference != 1) $periods[$j].= "s";
        $text = "$difference $periods[$j-1] ago";
        return $text;
    }
}

如果你看一下,我将单独留下阵列,这样你仍然可以将seconds放入你的返回值,但似乎这应该可以解决逻辑错误。