PHP中的重复功能

时间:2018-05-22 01:19:08

标签: php json function timing

所以我试图从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':'');
    }

}


在此先感谢:)

1 个答案:

答案 0 :(得分:1)

只需以非特定方式声明您的功能一次:

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);