PHP 中的重复函数

Duplicated function in PHP

所以我试图从一个 JSON Web 文件中获取两个 UNIX 时间戳,所以我想执行相同的操作 2 次(对于 2 个不同的时间戳)。 JSON 包含我希望在我的网站上使用的 2 个时间戳,但我不知道如何同时获取它们。我希望这一切都有意义...
这是我的代码;

$epoch_jd = $json["response"]["players"][0]["timecreated"]; //UNIX TIME STAMP
$readepoch_jd = gmdate('Y-m-d H:i:s', $epoch_jd);

$time_jd = strtotime($readepoch_jd);

function humanTiming ($time_jd)
{

    $time_jd = time() - $time_jd;
    $time_jd = ($time_jd<1)? 1 : $time_jd;
    $tokens_jd = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    foreach ($tokens_jd as $unit_jd => $text_jd) {
        if ($time_jd < $unit_jd) continue;
        $numberOfUnits_jd = floor($time_jd / $unit_jd);
        return $numberOfUnits_jd.' '.$text_jd.(($numberOfUnits_jd>1)?'s':'');
    }

}

这是我的另一个代码。

$epoch_ol = $json["response"]["players"][0]["lastlogoff"]; //UNIX TIME STAMP
$readepoch_ol = gmdate('Y-m-d H:i:s', $epoch_ol);

$time_ol = strtotime($readepoch_ol);

function humanTiming ($time_ol)
{

    $time_ol = time() - $time_ol;
    $time_ol = ($time_ol<1)? 1 : $time_ol;
    $tokens_ol = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    foreach ($tokens_ol as $unit_ol => $text_ol) {
        if ($time_ol < $unit_ol) continue;
        $numberOfUnits_ol = floor($time_ol / $unit_ol);
        return $numberOfUnits_ol.' '.$text_ol.(($numberOfUnits_ol>1)?'s':'');
    }

}


提前致谢:)

只需以非特定方式声明您的函数一次:

function humanTiming ($time)
{
    $time = time() - $time;
    $time = ($time<1)? 1 : $time;
    $tokens = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );
    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
    }
}

然后调用两次:

$epoch_jd = $json["response"]["players"][0]["timecreated"]; //UNIX TIME STAMP
$readepoch_jd = gmdate('Y-m-d H:i:s', $epoch_jd);
$time_jd = strtotime($readepoch_jd);
echo humanTiming($time_jd);

$epoch_ol = $json["response"]["players"][0]["lastlogoff"]; //UNIX TIME STAMP
$readepoch_ol = gmdate('Y-m-d H:i:s', $epoch_ol);
$time_ol = strtotime($readepoch_ol);
echo humanTiming($time_ol);