更改while循环以使echo不会打印多次

时间:2014-09-08 18:54:31

标签: php

我有一些代码可以回显while循环中的一行文本。但我不希望它作为一个循环,似乎没有while()可以让它工作。我的代码如下 - 如何才能让echo只打印一次?

while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
  do($row['InGarage'] == $comp and $row['BeingServiced'] == $unco and $row['ReadyForCollection'] == $unco) {
    echo "Vehicle is in Garage<br />";
}
  do($row['InGarage'] == $comp and $row['BeingServiced'] == $comp and $row['ReadyForCollection'] == $unco) {
    echo "Vehicle is being serviced<br />";
}
  do($row['InGarage'] == $comp and $row['BeingServiced'] == $comp and $row['ReadyForCollection'] == $comp) {
    echo "Vehicle is ready for collection<br />";
}
}

更新:使用if

while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {   
}

if($row['InGarage'] == $comp and $row['BeingServiced'] == $unco and $row['ReadyForCollection'] == $unco) {
    echo "Vehicle is in Garage";
} 
  if($row['InGarage'] == $comp and $row['BeingServiced'] == $comp and $row['ReadyForCollection'] == $unco) {
    echo "Vehicle is being serviced";
}
  if($row['InGarage'] == $comp and $row['BeingServiced'] == $comp and $row['ReadyForCollection'] == $comp) {
    echo "Vehicle is ready for collection";
}

1 个答案:

答案 0 :(得分:1)

不需要do运算符,但需要while来遍历数据库中的所有结果。使用do会更明智,而不是使用if。您还可以重构条件以创建稍短的条件:

while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
    if ($row['InGarage'] == $comp) {
        if ($row['BeingServiced'] == $comp) {
            if ($row['ReadyForCollection'] == $unco) {
                echo "Vehicle is being serviced<br />";
            }
            elseif ($row['ReadyForCollection'] == $comp) {
                echo "Vehicle is ready for collection<br />";
            }
        }
        elseif ($row['BeingServiced'] == $unco and $row['ReadyForCollection'] == $unco) {
            echo "Vehicle is in Garage<br />";
        }
    }
}

重构您的条件将使您的脚本不必进行额外的比较。在原始脚本中,每次都要测试$row['InGarage'] == $comp

if($row['InGarage'] == $comp and ... ) {
    echo "Vehicle is in Garage";
}
elseif($row['InGarage'] == $comp and ... ) {
    echo "Vehicle is being serviced";
}
elseif($row['InGarage'] == $comp and ... ) {
    echo "Vehicle is ready for collection";
}

测试一次然后测试其他条件更有效:

if($row['InGarage'] == $comp) {
    if ($row['BeingServiced'] == $unco and $row['ReadyForCollection'] == $unco) {
        (etc.)
    }
}