【问题标题】:PHP Unexpected String in a return of a function函数返回中的PHP意外字符串
【发布时间】:2021-10-11 06:25:15
【问题描述】:

我正在尝试创建一个函数来计算两个值的时间差,但是我在下面的代码中返回给我意外的字符串,怎么会?

            var mf_start_time   = "10:30:30";
            var mf_end_time     = "11:10:10";
            function time_interval(mf_start_time,mf_end_time)
            {
                $s = strtotime($start_time);
                $e = strtotime($end_time);
                if ($s < $e)
                {
                    $a = $e - $s;
                }
                else
                {
                    $e = strtotime('+1 day',$e);
                    $a = $e - $s;
                }
                
                $h = floor($a/3600);
                $m = floor(($a%3600)/60);
                $s = $a%60;
                
                return trim(($h?$h.' hour ':'').($m?$m.' minute ':'').($s?$s.' second ':''));
            }

【问题讨论】:

  • 这看起来像 javaScript 而不是 php,这意味着 $s.' second' 需要是 $s + ' second'
  • time_interval 函数中使用的方法,例如 trimfloorstrtotime 是 PHP 方法,因此连接方法将是句点 (.) 而不是加号签到(+)

标签: php string function return syntax-error


【解决方案1】:

您似乎确实混淆了 Javascript 和 PHP 的语法。 PHP 中没有 var - 它属于 Javascript,PHP 中的变量以 $ 开头

对您的代码进行一些小的调整:

$mf_start_time   = "10:30:30";
$mf_end_time     = "11:10:10";

function time_interval($mf_start_time,$mf_end_time)
{
    $s = strtotime($mf_start_time);
    $e = strtotime($mf_end_time);
    if ($s < $e)
    {
        $a = $e - $s;
    }
    else
    {
        $e = strtotime('+1 day',$e);
        $a = $e - $s;
    }
    
    $h = floor($a/3600);
    $m = floor(($a%3600)/60);
    $s = $a%60;
    
    return trim(($h?$h.' hour ':'').($m?$m.' minute ':'').($s?$s.' second ':''));
}

echo time_interval($mf_start_time,$mf_end_time);

产量:

39 minute 40 second

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多