如何在 PHP mysql 中按州和每行 3 个城市对头部进行分组



我有一个带有州,城市的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 列中分布城市

我对状态作为行标题有问题

任何帮助不胜感激

请尝试这个 -

步骤:

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

最新更新