我有一个如下所示的数据库表:
Business Phone City State Country
Baker 12345678 CityName 1 StateName 1 CountryName 1
Mason 91834919 CityName 2 StateName 2 CountryName 1
Welder 58149918 CityName 3 StateName 1 CountryName 1
Painter 48194918 CityName 4 StateName 3 CountryName 2
Chef 95982848 CityName 5 StateName 4 CountryName 3
Vendor 96928248 CityName 1 StateName 1 CountryName 1
我有这个 PHP 和 MySQL 在我的网页上生成一个无序列表:
<?$con = mysql_connect("localhost","root","testdb");
$db = mysql_select_db("table",$con);
$get=mysql_query("SELECT * FROM Sheet1 ORDER BY country,state,region,city ASC");
$result = '';
while($row = mysql_fetch_assoc($get))
{
$result .= "<ul class='tree'><li>" . $row['country'] . "<ul><li>" . $row['state'] . "<ul><li>" . $row['region'] . "<ul><li>" . $row['city'] . "<ul><li>" . $row['business'] . " | Phone #: " . $row['phone'] . "</li></ul></li></ul></li></ul></li></ul></li></ul>";
}?>
这是我的 html:
<?php echo $result; ?>
它的输出是这样的:
CountryName 1
- StateName 1
* CityName 1
* Vendor | 9692824
CountryName 1
- StateName 1
* CityName 1
* Baker | 12345678
CountryName 1
- StateName 1
* CityName 3
* Welder | 58149918
CountryName 1
- StateName 2
* CityName 2
* Mason | 91834919
CountryName 2
- StateName 3
* CityName 4
* Painter | 48194918
我希望它的输出是这样的:
CountryName 1
- StateName 1
* CityName 1
* Vendor | 9692824
* Baker | 12345678
* CityName 3
* Welder | 58149918
- StateName 2
* CityName 2
* Mason | 91834919
CountryName 2
- StateName 3
* CityName 4
* Painter | 48194918
CountryName 3
- StateName 4
* CityName 5
* Chef | 95982848
我必须做出哪些改变才能实现这一目标?
我想这比我目前写的要复杂得多。
最佳答案
在构建列表之前,您应该先将它们相应地分组(如您的结构所示),然后您可以构建列表。考虑这个例子:
<?php
$original_data = array();
$link = new MySQLI('localhost', 'username', 'password', 'database');
// normal select
$query = mysqli_query($link, 'SELECT * FROM Sheet1 order by country, state, city');
while($row = $query->fetch_assoc()) {
$original_data[] = $row;
}
$ordered_data = array();
foreach($original_data as $key => $value) {
// group them
$ordered_data[$value['country']][$value['state']][$value['city']][] = $value;
}
?>
<!-- print them accordingly -->
<?php foreach($ordered_data as $country => $state_values): ?>
<ul>
<li><?php echo $country; ?></li>
<?php foreach($state_values as $state => $city_values): ?>
<ul>
<li><?php echo $state; ?></li>
<ul>
<?php foreach($city_values as $city => $value): ?>
<li><?php echo $city; ?></li>
<ul>
<?php foreach($value as $index => $element): ?>
<li><?php echo $element['Business'] . ' | ' . $element['Phone']; ?></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
</ul>
</ul>
<?php endforeach; ?></li>
</ul>
<?php endforeach; ?>
关于php - 如何重写我的 PHP 和 MySQL 以按相等的列值对我的 HTML 列表进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24194009/