![](/img/trans.png)
[英]MySQL Query with multiple GROUP BY - How do I make one group a column head and one group a row head in an HTML table?
[英]How to group head by state and 3 city per row in PHP mysql
我有一个带有状态,城市的mysql表。
我的查询是这样的:
$result = mysqli_query($con, "select * from " . $loc_tbl . " order by city ASC");
echo "<html><head></head><body>
<table>";
$num_columns = 3;
$num_rows = mysqli_num_rows($result);
$i=0;
while($row = mysqli_fetch_assoc($result)){
$results[$i] = $row['city'];
$i++;
}
unset($i);
$k=0;
for ($i=0;$i<=($num_rows/($num_columns+1));$i++){
echo '<tr>';
for($j=1;$j<=$num_columns;$j++){
echo '<td>'.$results[$k].'</td>';
$k++;
}
echo '</tr>';
$k++;
}
echo "</table></body>
</html>";
想要显示状态为标题
California
---------------------------------------
San Jose | Santa Clara | Palo Alto
---------------------------------------
Los Angeles | Orange County | Los Gatos
---------------------------------------
New Jersey
---------------------------------------
Morristown | Union | Summit
---------------------------------------
Newark | Parsipenny | Atlantic City
能够将城市分布在每行3列
我将STATE作为ROW HEADER遇到问题
任何帮助表示赞赏
请尝试这个-
脚步:
1)将行数据转换为数组,以使状态成为具有城市数组值的键
2)显示为$ num_columns定义的值
$result = mysqli_query($con, "select * from " . $loc_tbl . " order by city ASC");
$num_columns = 3;
/* Step 1 :
* $rows will be array having
* State as key and array of cities as value
*/
$rows = array();
while($row = mysqli_fetch_assoc($result)){
if(!isset($rows[$row['state']])){
$rows[$row['state']] = array();
}
$rows[$row['state']][] = $row['city'];
}
/* Step 2 :
* Following table will have columns with respect to value defined for $num_columns
*/
echo "<table>";
foreach($rows as $state => $cities){
echo '<tr><th colspan="'. $num_columns .'">'. $state .'</th></tr>';
$cityChunks = array_chunk ($cities, $num_columns); // split array into chunk of $num_columns cities per array
foreach($cityChunks as $row){
echo "<tr>";
for($i=0; $i<$num_columns; $i++){
$city = isset($row[$i]) ? $row[$i] : "";
echo "<td>$city</td>";
}
echo "</tr>";
}
}
echo "</table>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.