如何在PHP mysql中按州和每行3个城市分组
我有一个带有state和city的mysql表 我的问题是这样的:如何在PHP mysql中按州和每行3个城市分组,php,mysql,html-table,Php,Mysql,Html Table,我有一个带有state和city的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);
$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>";
我能够将城市分布在每行3列中
我对行标题的状态有问题
感谢您的帮助请尝试以下内容-
步骤:
1将行数据转换为数组,这样状态将是具有城市数组值的键
2显示为$num_列定义的值
请仔细阅读,我们是来帮助解决问题的,而不是为您编写完整的代码。抱歉@Naruto,我可以在3个html表格列中显示城市,但缺少行标题逻辑。你能帮忙吗?我爱你,谢克哈比斯兄弟。我工作过。感谢AlotGlad帮助@bgb76,如果此答案解决了您的问题,请单击答案旁边的复选标记将其标记为已接受。有关更多信息,请参阅
California
---------------------------------------
San Jose | Santa Clara | Palo Alto
---------------------------------------
Los Angeles | Orange County | Los Gatos
---------------------------------------
New Jersey
---------------------------------------
Morristown | Union | Summit
---------------------------------------
Newark | Parsipenny | Atlantic City
$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>";