2012-06-25 41 views
0

如果我禁用错误,此功能正常工作。但我必须解决它们。 所以我启用了错误,并发现了以下错误:错误:未定义的变量:retval和未定义的常量长度 - 假定'长度'

Notice: Undefined variable: retval in /home/content/79/9482579/html/gamelinkexchange.com/all/function.php on line 20

Notice: Use of undefined constant length - assumed 'length' in /home/content/79/9482579/html/gamelinkexchange.com/all/function.php on line 55

这里是我的功能:

function time_ago($date,$granularity=2) { 
date_default_timezone_set('Asia/Calcutta'); 
    $date = strtotime($date); 
    $difference = time() - $date; 
    $periods = array('decade' => 315360000, 
     'year' => 31536000, 
     'month' => 2628000, 
     'week' => 604800, 
     'day' => 86400, 
     'hour' => 3600, 
     'minute' => 60, 
     'second' => 1); 
foreach ($periods as $key => $value) { 
     if ($difference >= $value) { 
      $time = floor($difference/$value); 
      $difference %= $value; 
      $retval .= ($retval ? ' ' : '').$time.' '; /*error*/ 
      $retval .= (($time > 1) ? $key.'s' : $key); 
      $granularity--; 
     } 
     if ($granularity == '0') { break; } 
    } 
    return $retval.' ago';  
} 
function gethours($str) 
{ 
    if(strpos($str, "decade")) 
    { 
     return 0; 
    } 
    else if(strpos($str, "year")) 
    { 
     return 0; 
    } 
    else if(strpos($str, "month")) 
    { 
     return 0; 
    } 
    else if(strpos($str, "week")) 
    { 
     return 0; 
    } 
    else if(strpos($str, "day")) 
    { 
     return 0; 
    } 
    else if(strpos($str, "hours")) 
    { 
     $strarr= explode(" ",$str); 
     $j=0; /*error*/ 
     for($i=0;$i<$strarr.length;$i++) 
     { 
      if($strarr[$i]=="hours") 
      { 
       $j=$i-1; 
      } 
     } 
     return $strarr[$j]; 
    } 
else { return 1; } 
} 

此功能运行速度非常慢,所以我需要解决这些错误。我尝试了本网站和其他论坛的其他页面提供的解决方案,但没有任何帮助。请提供一个消耗较少资源的好解决方案。
我需要一个解决方案。因为每个条目都必须消磨时间。

这是我的第一个问题,我是新手,请大家帮忙。谢谢。

+2

这实在不是一个 “做我的工作对我来说” 的网站,这个问题似乎特别适合于为你完成工作,而不是提出一个对未来访问者有用的问题。 – cdhowie

回答

1

我看不到你在任何地方初始化你的$retval。根据其值,您应该在开始附加任何内容之前,可能有类似$retval = ''的内容。

关于其他错误,你就错了PHP的Java。在PHP中,你得到一个数组的长度与count($strarr)代替$strarr.length

更新
而不是

$retval .= ($retval ? ' ' : '').$time.' '; 

,你可以简单地使用

$retval = $time.' '; 
+0

我应该使用什么值来初始化$ retval =''。或使用它完全相同.. –

+0

@Asim只要摆脱'($ retval?'':'')''。这是没用的,因为'$ retval'在这一点上没有定义。 – deceze

+0

所以我必须删除它。我应该用什么来代替它。 –

0

更改行:

$retval .= ($retval ? ' ' : '').$time.' '; /*error*/ 

要这样:

$retval .= (isset($retval))? ' ':''; 
$retval .= $time.' '; //you shouldn't have the error on that line again -- it's because 
//the variable does not exist and you're sing it in a comparison 

更改下面这行:

for($i=0;$i<$strarr.length;$i++) 

要这样:

for($i=0;$i<count($strarr);$i++){....} 
//arrays in PHP cannot be used like objects (-> not .) 
+0

第一个错误“$ retval”错误是相同的“未定义的变量:retval”请帮助。感谢解决我的第二个错误。第一个错误: –

+0

:我完全错过了...它应该是'$ retval =(isset($ retval))? '':'';'不'$ retval。=(isset .......)' –

+0

只需将'。='改为'='。让我知道它是否有效:) –