[英]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.