2010-10-28 121 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)";