【问题标题】:Duplicated function in PHPPHP中的重复函数
【发布时间】:2018-05-22 01:19:07
【问题描述】:

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

}


在此先感谢:)

【问题讨论】:

  • 这两个功能不一样吗?为什么需要重新定义它?
  • 参数名称不同,但不影响函数的使用方式。只需定义一次,然后从两个地方调用它。
  • 不要害怕 DateTime 类——它不会伤害你。您肯定已经研究过 StackOverflow 上的许多“人类可读时间”页面。

标签: php json function timing


【解决方案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);

【讨论】:

  • 不,非常完美,谢谢,我只是函数新手 :) 谢谢尼克
  • 太好了。很高兴能帮上忙。
猜你喜欢
  • 2017-11-21
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多