好吧,我不知道如何更好地表达标题,但希望我可以在这里更好地解释:
我有一个动物数据库,有几列,其中一列名为 Category
,其中包含单个单词字符串,例如 frog
或 newt
.
我可以在两个单独的查询中成功地在数据库中查询这些内容并分别打印结果,但理想情况下我希望使用单个查询,然后分割数据以将结果打印到页面上,但分两部分,一个一种用于 Frog ,一种用于蝾螈。
目前我的代码如下所示:
$query = "SELECT * FROM livestock WHERE Category = 'frog' OR Category = 'newt'";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
echo"<div class='rowtable'>";
while($row = mysqli_fetch_array($result)){
$commondraft = $entry['Name'];
echo"<a href='/stocklist/".$entry['id']."/".commonName($commondraft)."' class='row'>";
echo"<div class='common'>".$entry['Name']."</div>";
echo"<div class='descr'>".$row['Description']."</div>";
echo"<div class='sex'>".$row['Sex']."</div>";
echo"<div class='age'>".$row['Age']."</div>";
echo"<div class='size'>".$row['Size']."</div>";
echo"<div class='origin'>".$row['Origin']."</div>";
echo"<div class='scientific'>".$row['Scientific']."</div>";
echo"<div class='prices'>".$row['Price']."</div>";
echo"</a>";
}
echo"</div>";
这显然会打印出frog
和newt
两个类别的所有条目。如何在此处仅选择一个类别,然后在其他地方使用另一个类别,而无需重新查询数据库以获取剩余类别?
最佳答案
您可以按照其他人的建议进行操作(按类别排序
),但我认为这将是更好的解决方案:当您从livestock
表中检索项目时,您可以将它们放入每个类别都有单独的数组。我的意思是,您可以使用 $items 数组(在我的示例中)作为字典( HashMap ),其中键是类别名称,值是属于该类别的所有项目的数组。稍后,当您想要输出某个类别中的项目时,只需使用所需类别调用 output
函数即可。例如(我简化了输出;您可以将其用于任意数量的类别。您只需更改 getItems
中的 $query
):
function getItems($con) {
$items = array();
$query = "SELECT * FROM livestock WHERE Category = 'frog' OR Category = 'newt'";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
while($row = mysqli_fetch_array($result)) {
$category = $row['Category'];
if (!isset($items[$category])) {
$items[$category] = array();
}
array_push($items[$category], $row);
}
return $items;
}
function output($category, $items) {
echo"<div class='rowtable'>";
foreach ($items[$category] as $entry) {
echo"<div class='common'>".$entry['Name']."</div>";
}
echo"</div>";
}
$items = getItems($con); // $con holds connection to database
output('frog', $items); // prints just items from frog category
output('newt', $items); // prints just items from newt category
关于php - 显示按类别分组的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26956558/