开发者

how to echo the line one time under the while loop

I have a code like this

<?php

$getLeftSide = 'select * from leftmenu';

$result = $db -> query ($getLeftSide) or die ("$db->error");

if ($result) {

    while ($row = $result -> fetch_object()) {

        $getCat = $row -> left_item_cat;



        if ($getCat == 1) {
    echo "<div class='left_main_cat'>Web and Desigen</div>";
    echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";

        }
      }
    }



?>开发者_如何转开发

I need to echo this line one time

echo "<div class='left_main_cat'>Web and Design</div>";

of course it's under the while loop so it print it self many times is there is a why to solve this and print this line one time only.


As Ben suggests, the easiest and clearest solution is to use a boolean check variable:

$catFound = FALSE;
while ($row = $result -> fetch_object()) {

    $getCat = $row -> left_item_cat;

    if ($getCat == 1) {
        // We only want this category printed for the first category,
        // if it exists.
        if(!$catFound) { 
            echo "<div class='left_main_cat'>Web and Desigen</div>";
            $catFound = TRUE;
        }
        echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
    }
}

Although it seems better to use a boolean variable and a comment to make clear your intent.


Ugly, but I'm not that good at PHP yet!

$has_printed = FALSE;
while ($row = $result -> fetch_object()) {

    $getCat = $row -> left_item_cat;

    if ($getCat == 1) {
if(!$has_printed){
echo "<div class='left_main_cat'>Web and Desigen</div>";
$has_printed = TRUE;
}
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";

    }
  }


Simple solution: Add another boolean variable with default value false Then just check if false, print your text and set it true.


adding a boolean or check variable or any kind of conditional inside of a loop is a very bad idea imho, i NEVER do it. every time you swing through the loop, the condition has to be checked. it's like a badly written switch/case.

figure out a way to do it before the loop.

  1. unroll the loops, most people do it to save space but most compilers will unroll them anyway for optimization

  2. stick it before the loop

  3. find a java or css way to hide it until the loop is done or you want to display stuff.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜