2012-06-25 36 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

只需將'。='改爲'='。讓我知道它是否有效:) –