本文介绍了如何在PHP中使用while循环列出具有相同ID的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mysql表.像这样的专栏

I have a mysql table. column like that

series_id, series_color, product_name

我应该列出与组相同的series_id product.

I should list same series_id product like with group.

我想要像这样的列表,所有相同的saries_id像这样在我的屏幕上回声

I want like that list all same saries_id echo my screen like that

A12 Series Product

 - Milk  
 - Tea 
 - sugar
 - water

B12 Series Product

 - Water 
 - Banana 
 - Cofee 
 - Tea

推荐答案

series_id排序结果,因此具有相同值的所有产品都将在一起.

Order your results by series_id, so all the products with the same value will be together.

$stmt = $pdo->prepare("SELECT series_id, product_name
                       FROM yourTable
                       ORDER BY series_id");
$stmt->execute();

然后在显示结果时,显示Series标头,并在更改时开始新的<ul>:

Then when displaying the results, show the Series header and start a new <ul> whenever it changes:

$last_series = null;
echo "<ul>\n";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if ($row['series_id'] != $last_series) {
        if ($last_series) {
            echo "</ul></li>\n";
        }
        echo "<li>" . $row['series_id'] . " Series Product\n";
        echo "<ul>\n";
        $last_series = $row['series_id'];
    }
    echo "<li>" . $row['product_name'] . "</li>\n";
}
if ($last_series) {
    echo "</li>\n";
}
echo "</ul>\n";

这篇关于如何在PHP中使用while循环列出具有相同ID的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 00:59