php - 将 SQL 结果分类并在表格 PhP 中显示

标签 php mysql sql sorting categories

我想在 PHP/HTML 表中显示这样的 MySQL 结果。如果以后容易的话,也许可以为每个植物添加鼠标悬停信息。

+-----------------------------------------------------------+
|category1  ¦ category2 ¦ category3 ¦ category4 ¦ category5 ¦ 
+-----------+-----------+-----------+-----------+-----------+
| plantName ¦ plantName ¦ plantName ¦ plantName ¦ plantName ¦ 
| plantName ¦ plantName ¦ plantName ¦ plantName ¦ plantName ¦ 
| plantName ¦ plantName ¦           ¦           ¦           ¦
|           ¦ plantName ¦           ¦           ¦           ¦
|           ¦ plantName ¦           ¦           ¦           ¦
+-----------+-----------+-----------+-----------+-----------+

First I select plants by elevation and rainfall values.

$sql = mysql_query("SELECT * FROM `plants_tb` 
WHERE $elevate>= elevationLOW  &&  $elevate<= elevationHI &&
$rainfall>= rainfallLOW  &&  $rainfall<= rainfallHI ORDER BY commonNames ASC");

$plant = 'commonNames';
$elevationH = 'elevationHI';
$elevationL ='elevationLOW';
$rainfallL ='rainfallLOW';
$rainfallH ='rainfallHI';
$species ='species';

echo "<table border='1'><tr><th>Name</th><th>Category</th></tr>";
while($row = mysql_fetch_array($sql)){
echo "<tr><td>" . $row[$plant] . "</td><td>" . $row['heightHI'] . "</td></tr>";
}
echo "</table>";

现在我需要按高度类别将它们显示在列中。或许我应该将所选植物制作一个临时表格,然后将它们分类,然后按列显示? 这是我的分类想法。我知道代码之间的这种做法是不正确的,但它表明了我的观点。

$sql="SELECT tree_height FROM $Elevation_Rainfall_list;
WHERE tree_height
BETWEEN 1 AND 7 = $Category1
BETWEEN 7 AND 15 = $Category2
BETWEEN 15 AND 30 = $Category3
BETWEEN 30 AND 9999 = $Category4
if not = $Category5

mahalo 的支持!

最佳答案

看起来你想创建类似直方图的东西。

与其尝试在 SQL 查询中对数据进行分类,不如在 PHP 中使用类似这样的方法来完成:

$histogram = array();
# classify the data into histogram bins
while($row = mysql_fetch_array($sql)) {
    $h = $row['tree_height'];
    $cat = 3;
    if ($h <= 7) {
        $cat = 0;
    } elseif ($h <= 15) {
        $cat = 1;
    } elseif ($h <= 30) {
        $cat = 2;
    }
    $histogram[$cat][] = $row['commonNames'];
}

# determine the number of rows in the table
$rows = 0;
foreach ($histogram as $ar) { $rows = max($rows, count($ar)); }

# write a table with the data
echo "<table border='1'>\n" .
     "  <tr>\n    <td>Category 1</td>\n    <td>Category 2</td>\n" .
     "    <td>Category 3</td>\n    <td>Category 4</td>\n</tr>\n";
for ($i = 0; $i < $rows; ++$i) {
    echo "  <tr>\n";
    for ($cat = 0; $cat <= 3; ++$cat) {
        echo "    <td>" . $histogram[$cat][$i] . "</td>\n";
    }
    echo "  </tr>\n";
}
echo "</table>\n";

关于php - 将 SQL 结果分类并在表格 PhP 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13715019/

相关文章:

sql - 如何在 Entity Framework 5 中使用基于 SQL session 的表

MySQL 从具有规范的文本列中选择

sql - 如何将旧备份从 SQL Server 7 SP4 还原到最新的 SQL Server 版本?

php - 如何在 Visual Studio Code (VSCode) 上运行或调试 php

mysql - 从 MySQL 表中删除重复值的最佳方法是什么?

php - 如何将访问 token 附加到 Google 日历 API 请求

MySQL 函数根据数据数组将字符串评估为整数

mysql - WHERE 有两个子条件

php - 拉拉维尔 : php artisan not working

SQL 选择器上的 PHP 函数