2010-10-28 116 views
0
$counter = ""; 
if($sWall>1){ 
    $counter = $counter + $sWall; 
} 
if($sWC>1){ 
    $counter = $counter + $sWC; 
} 
if($sOther>1){ 
    $counter = $counter + $sOther; 
} 
if(!(empty($counter))){ 
    echo "(".$counter.") "; 
} 

這就是我所沒有的。 $sOther,$sWC,$sWallmysql_num_rows。如果你有$sOther中的1,$sWC中的1和$sWall中的1,我希望回顯出來,例如(3)。設置變量和計數

我該怎麼做,我所做的只是我嘗試過的。

+0

它是如何「不工作」?錯誤? (如果是這樣,請將其編輯到問題中)意外的輸出? (如果是這樣,請告訴我們是什麼。) – GreenMatt 2010-10-28 19:54:53

回答

1
$counter = $sWall + $sWC + $sOther; 
if ($counter) { 
    echo '(' . $counter . ')'; 
} 

就是這樣;)記住:簡碼是很好的代碼。

3

計數器是一個字符串類型。第一行應該是$counter = 0;。 你應該改變if ($sWall>1)if ($sWall>0)等等...

0

在上面的代碼中,$計數器不會增加,如果任何檢查值等於1,您應該使用if($ SWALL * > = * 1)。只需添加$sWall + $sWC + $sOther

0
$counter = 0; 
if($sWall>0){ 
    $counter = $counter + $sWall; 
} 
if($sWC>0){ 
    $counter = $counter + $sWC; 
} 
if($sOther>0){ 
    $counter = $counter + $sOther; 
} 
if($counter>0){ 
    echo "(".$counter.") "; 
} 

,如果你想存儲的數字使用int,所以你可以檢查它是否大於零,並呼應它,它可能會更容易。

請注意,您也可以編寫$counter += $sWall;而不是$counter = $counter + $sWall;,因此您不必輸入太多。

0

將數值初始化爲0。這不是問題的根源,因爲當您使用數字運算符(如+)時,PHP會將空字符串轉換爲0,但在語義上,最好說明$counter是數字。

添加完值後,測試$counter是否大於0,而不是使用empty。您可以使用速記+=操作員並簡單測試$counter以使整個方法更簡潔一點。

最後,您選擇了錯誤的比較運算符(>)來測試您的值。如果你想包括1,使用>=

$counter = 0; 
if($sWall >= 1) $counter += $sWall; 
if($sWC >= 1) $counter += $sWC; 
if($sOther >= 1) $counter += $sOther; 

if ($counter) 
    echo "($counter)";