假设我有一个名为'products'的数据库,其字段为'id','desc','categ':( 1,'Banana','fruit'),(2,'Apple','fruit') ,(3,'番茄','蔬菜'),(4,'水','饮料')。
我如何执行或更好地:评估对此数据库的查询,以便我可以根据其类别将结果拆分为多个部分?我的目标是我可以插入一些标题,如
等等。
基本代码就像
$con = mysqli_connect(/*etc.*/);
$result = mysqli_query('SELECT * FROM products ORDER BY `categ`');
mysqli_close($con);
while($row = mysqli_fetch_array($result)) {
// How to handle this?
}
答案 0 :(得分:1)
有很多种方法,但你可以收集数组中所有不同的类别,以便以后显示/操作:
while($row = mysqli_fetch_array($result)) {
if ($row['categ'] == "fruit") $fruit_array[] = $row['desc'];
elseif ($row['categ'] == "vegetables") $vegetable_array[] = $row['desc'];
//etc...
}
以后你可以:
echo "<h1>Fruit</h1>";
foreach ($fruit_array as $fruit) {
echo $fruit."<br>";
} //etc...
答案 1 :(得分:0)
这是我的方法:
$con = mysqli_connect(/*etc.*/);
$result = mysqli_query('SELECT * FROM products ORDER BY `categ`');
mysqli_close($con);
//Assigning a temporary variable to hold current category
$previousCategory = '';
while($row = mysqli_fetch_array($result)) {
$thisCategory = $row['categ'];
//Comparing this category with previous one
if($thisCategory != $previousCategory) {
//Printing category as title
echo '<b>'.$thisCategory.':</b><br />';
}
//Printing product
echo $row['product_name'].' ';
//Now storing this category to compare with next one
$previousCategory = $thisCategory;
}