在一个循环之后迭代mysql表的问题

问题描述 投票:-2回答:1

我有2张桌子。第一个是categories,第二个是items。我需要我的脚本在.txt文件中打印类别的名称,并在其下面的类别项目中匹配'category_id'。我的代码使用第一个while循环遍历类别,第二个迭代遍历项目。一切正常,直到我们到达第二个while循环,因为那时值变为空。

while ($row2 = mysqli_fetch_array($query_for_categories)) {
    fwrite($fp, $row2["category_name"].PHP_EOL);
    while ($row = mysqli_fetch_array($query_for_items)) {
        if ($row2['id_category_from_category'] == $row['id_category_from_items']) {
            fwrite($fp, $row["item_name"].PHP_EOL);
        }
    }
}
php
1个回答
1
投票

在外部while循环的第一次迭代之后,您将从$query_for_categories获取所有行。在外部while循环的后续迭代中,将不再有来自该查询的行。

您可以先将它们全部提取到数组中

while ($row = mysqli_fetch_array($query_for_items)) {
    $items[] = $row;
}

然后使用该数组中的行而不是while ... fetch循环。

while ($category = mysqli_fetch_array($query_for_categories)) {
    fwrite($fp, $category["category_name"].PHP_EOL);
    foreach($items as $item) {
        if ($category['id_category_from_category'] == $item['id_category_from_items']) {
            fwrite($fp, $item["item_name"].PHP_EOL);
        }
    }
}

不过,看起来您可能会使用一个连接进行一次查询。我建议检查一下,而不是这样做。根据代码中的列名,查询将如下所示:

SELECT c.category_name, i.item_name
FROM categories c
  LEFT JOIN items i on c.id_category_from_category = i.id_category_from_items
ORDER BY c.category_name, i.item_name

然后你可以在一个循环中打印带有类别的项目,如下所示:

$previous_category = null;

while ($item = mysqli_fetch_array($query)) {

    // each time category changes, output the new category name
    if ($item['category_name'] != $previous_category) {
        fwrite($fp, $item["category_name"].PHP_EOL);

        // then current category becomes previous category
        $previous_category = $item['category_name'];
    }
    fwrite($fp, $item["item_name"].PHP_EOL);
}

我想知道如何判断文件中的哪些行是项目,哪些是类别。也许你应该为此输出某种指标?

© www.soinside.com 2019 - 2024. All rights reserved.