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

How to remove division by zero from this function?

我用这个php函数将数字时间戳转换成类似“7天前”的东西,但是某个时间戳returns 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];,但我不知道如何修复函数以避免这个错误。

如果超过十年会怎样?

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

问题是您的循环在到达 $lengths 的末尾时没有停止。当$i到达数组长度时,$lengths[$i]未定义,除法时转换为0

您可以使用 foreach 代替 for

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

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

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 放入你的 return 值中,但看起来这应该可以解决逻辑错误。