3

I want to display MySQL results like this in a PHP/HTML table. Maybe add mouse over info for each plant if thats easy later.

+-----------------------------------------------------------+
|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>";

Now I need to display them in columns by height categories. Maybe I should make a temporary table of the selected plants, then categorize them, then display them in columns? Here is my idea for categorizing. I know this between code is not correct but, it gets my point out.

$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 for the support!

4

1 回答 1

3

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

与其尝试在 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";
于 2012-12-05T03:14:47.217 回答