简体   繁体   English

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

[英]Foreach inside of While Loop Looks Funny

I keep getting a wierd list after running this: 运行此命令后,我一直得到一个奇怪的列表:

<?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); ?>

I have a categories table with id & category and a sub categories table with a id, subcategory, & primary category id. 我有一个具有ID和类别的类别表,以及一个具有ID,子类别和主要类别ID的子类别表。 I run it and it displays the foreach first randomly. 我运行它,它首先随机显示foreach。

My head really hurts from your code, but i believe your problem is here: 我的头真的很受您的代码的伤害,但是我相信您的问题在这里:

$cat = $row_getCategory['cat_id'];

$row_getCategory is fetched at the end of your code, so this code just can not work. $ row_getCategory是在代码末尾获取的,因此该代码无法正常工作。

I believe you want to do something like this 我相信你想做这样的事情

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>';
    }

    }

}

There are times where it's ok to have a foreach within a while , but this isn't one of them. 有时在一段while内可以进行foreachwhile ,但这不是其中之一。 First off you are doing a do ... while loop which means regardless if a row is found or not, you will step through all the code, so if no row exists in database, you will probably get undefined index errors. 首先,您正在执行do ... while循环,这意味着无论是否找到行,您都将逐步执行所有代码,因此,如果数据库中不存在行,则可能会出现undefined index错误。 Secondly you are executing the subcategory query for every iteration of the outer while loop, which means that if your query returns 100 rows, you are issuing 100 queries, not good. 其次,您要为外部while循环的每次迭代执行子类别查询,这意味着如果查询返回100行,那么您将发出100个查询,这不好。

Your best bet is to create a join between the two tables and step through the rows in one loop, preferably a while loop (vs a do ... while loop). 最好的选择是在两个表之间创建联接,并在一个循环中逐步遍历各行,最好是while循环(与do ... while循环相比)。

Something like this: 像这样:

// 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';

Now you only have a single query which retrieved all categories and their associated sub-categories, now you can step through them with a single while loop: 现在,只有一个查询可以检索所有类别及其关联的子类别,现在可以通过一个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>';
    }
}

You don't need to do a separate subquery for each category. 您无需为每个类别执行单独的子查询。 Just do a join. 只需加入即可。 Try this: 尝试这个:

$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>";

I think you should not use do while to retrieve the data from the database.You should rather use while loop because, do while runs the loops once before checking the condition.So at the first loop, you will not get any data in the echo $row_getCategory['category']; 我认为您不应该使用do while从数据库中检索数据,而应该使用while循环,因为do while在检查条件之前运行一次循环,因此在第一个循环中,您将不会在echo $row_getCategory['category'];获取任何数据echo $row_getCategory['category']; variable. 变量。 So please try using the following code : 因此,请尝试使用以下代码:

<?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
} 
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM