While循环中的Foreach看起来很有趣

时间:2012-04-20 05:21:49

标签: php loops foreach while-loop

我在运行这个后继续得到一个奇怪的清单:

<?php 
  $query_Category = "SELECT * FROM blog_categories ORDER BY category ASC";

  $getCategory = mysql_query($query_Category) or die(mysql_error()); 
?>

<div id="sheader" style="">Categories</div>

<div class="sbody" style="color:#000 !important;">

<?php 
   do { 
?>
    <div><?php echo $row_getCategory['category'];?></div>

<?php 
    $cat = $row_getCategory['cat_id'];

    $query_Subcategory = "SELECT * FROM blog_subcategories WHERE primcat_id = '$cat' ORDER BY subcategory ASC";

    $getSubCategory = mysql_query($query_Subcategory) or die(mysql_error());
    $row_getSubCategory = mysql_fetch_assoc($getSubCategory);

    $str = $row_getSubCategory['subcategory']; $subcategory = explode(',', $str);

    foreach ($subcategory as $arraysubcat) 
    {
       echo '<div>' . $arraysubcat . '</div>';
    }
    } while ($row_getCategory = mysql_fetch_assoc($getCategory)); 
?>

</div>
<?php mysql_free_result($getCategory); ?>

我有一个id&amp;的类别表类别和具有id,子类别和&amp;的子类别表主要类别ID。 我运行它,它首先随机显示foreach。

4 个答案:

答案 0 :(得分:2)

您不需要为每个类别执行单独的子查询。加入吧。试试这个:

$db = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

$get_categories = $db -> query("SELECT category, subcategory 
                    FROM blog_categories, blog_subcategories
                    WHERE primcat_id = cat_id
                    ORDER BY category ASC, subcategory ASC");

echo "<h1>Categories</h1>";

echo "<ul>";

while($row = $get_categories -> fetch_assoc()) {
    echo "<li>" . $row['category'];
    if($row['subcategory']) {
        echo "<ul>";
        foreach(explode(",",$row['subcategory']) as $subcategory ) {
            echo "<li>$subcategory</li>";
        }
        echo "</ul>";
    }
    echo "</li>";
}

echo "</ul>";

答案 1 :(得分:1)

我的头脑真的很伤你的代码,但我相信你的问题就在这里:

$cat = $row_getCategory['cat_id'];

$ row_getCategory是在代码末尾提取的,所以这段代码无法正常工作。

我相信你想做这样的事情

while ($row_getCategory = mysql_fetch_assoc($getCategory))
{
    $cat = $row_getCategory['cat_id'];

    $query_Subcategory = "SELECT * FROM blog_subcategories WHERE primcat_id = '$cat' ORDER BY subcategory ASC";

    $getSubCategory = mysql_query($query_Subcategory) or die(mysql_error());
    $row_getSubCategory = mysql_fetch_assoc($getSubCategory);

    $str         = $row_getSubCategory['subcategory'];
    $subcategory = explode(',', $str);

    foreach ($subcategory as $arraysubcat) {
        echo '<div>' . $arraysubcat . '</div>';
    }

    }

}

答案 2 :(得分:1)

有时可以在foreach内设置while,但这不是其中之一。首先,您正在执行do ... while循环,这意味着无论是否找到行,您都将逐步执行所有代码,因此如果数据库中不存在任何行,则可能会出现undefined index错误。其次,您正在为外部while循环的每次迭代执行子类别查询,这意味着如果您的查询返回100行,则发出100个查询,这不是好事。

最好的办法是在两个表之间创建一个连接,并在一个循环中逐步执行这些行,最好是一个while循环(相对于do ... while循环)。

这样的事情:

// Made some assumptions with the query, as no schema was posted
// But should give you a starting point
$sql = 
'SELECT bc.*, GROUP_CONCAT(bsc.subcategory) AS sub_categories ' .
'FROM blog_categories AS BC INNER JOIN blog_subcategories AS bsc ON bsc.primcat_id = bc.id ' .
'GROUP BY bc.id ' .
'ORDER BY bc.category ASC';

现在您只有一个查询检索了所有类别及其关联的子类别,现在您可以通过一个while循环逐步执行它们:

$query = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_assoc($query)) {

    <div>
      <?php echo $row['category']; ?>
    </div>

    // To get at subcategories you can do this
    $subCategories = array_map('trim', explode(',', $row['sub_categories']));

    // And sort them ASC
    sort($subCategories);

    foreach ($subCategories as $subCategory) {
        echo '<div>' . $subCategory . '</div>';
    }
}

答案 3 :(得分:0)

我认为你不应该使用do while从数据库中检索数据。你应该使用while循环,因为do while在检查条件之前运行一次循环。所以在在第一个循环中,您不会在echo $row_getCategory['category'];变量中获得任何数据。所以请尝试使用以下代码:

<?php
while ($row_getCategory = mysql_fetch_assoc($getCategory)){
?>
        <div>
          <?php
            echo $row_getCategory['category'];      
           ?>
        </div>
        <?php
            $cat = $row_getCategory['cat_id'];

            $query_Subcategory = "SELECT * FROM blog_subcategories WHERE primcat_id = '$cat' ORDER BY subcategory ASC";

            $getSubCategory = mysql_query($query_Subcategory) or die(mysql_error());
            $row_getSubCategory = mysql_fetch_assoc($getSubCategory);

            $str         = $row_getSubCategory['subcategory'];
            $subcategory = explode(',', $str);

            foreach ($subcategory as $arraysubcat) {
                echo '<div>' . $arraysubcat . '</div>';
            }
        ?>
<?php
} 
?>