gpt4 book ai didi

php - MYSQL + PHP 将两行数据显示为单列

转载 作者:行者123 更新时间:2023-11-29 14:07:17 25 4
gpt4 key购买 nike

我有一个包含以下格式数据的表格

region   gender  age_group  population 

Dallas M 1 200
Dallas F 1 500
NY M 1 320
NY F 1 310
Dallas M 2 300
Dallas F 2 600
NY M 2 400
NY F 2 800

我正在寻找以以下格式输出数据的最佳查询

region/age_group      1           2
Gender M F M F
Dallas 200 500 300 600
NY 320 310 400 800

我的查询仅返回顶部列和区域。不确定如何将顶栏分割为性别,如上面所示

SELECT distinct (region), a.group_one, b.group_two 
FROM city_populations c
LEFT JOIN city_populations AS a ON a.age_group=1 AND c.age_group=a.age_group
LEFT JOIN city_populations AS b ON b.age_group=2 AND c.age_group=a.age_group

最佳答案

//首先我从数据库中获取所有数据

$result = mysql_query("select * from test2")or die(mysql_error());
$regions = array();
$age_groups = array();
while($det = mysql_fetch_array($result)){

if(!in_array($det['region'], $regions)){
$regions[] = $det['region'];
}
if(!in_array($det['age_group'], $age_groups)){
$age_groups[] = $det['age_group'];
}
$rows[] = $det;
}

//然后在php中处理以显示为你想要的

echo "<table>";
echo "<tr><td>Age group</td>";
foreach($age_groups as $keyAG => $valueAG){
echo "<td colspan='2'>$valueAG</td>";
}
echo "</tr>";
echo "<tr><td>Gender</td>";
foreach($age_groups as $keyAG => $valueAG){
echo "<td>M</td>";
echo "<td>F</td>";
}
echo "</tr>";
foreach($regions as $keyR => $valueR){

echo "<tr>";
echo "<td>".$valueR."</td>";
foreach($age_groups as $keyAG => $valueAG){

foreach($rows as $keyROWS => $valueROWS){
if($valueROWS['region'] == $valueR && $valueROWS['age_group'] == $valueAG){
if($valueROWS['gender'] == 'M'){
echo "<td>".$valueROWS['population']."</td>";
}
elseif($valueROWS['gender'] == 'F'){
echo "<td>".$valueROWS['population']."</td>";
}
}
}
$data[$valueR][$valueAG] = array($maleValue, $femaleValue);

}
echo "</tr>";
}
echo "</table>";

注意:强烈建议使用 mysqli_* 而不是 mysql。

关于php - MYSQL + PHP 将两行数据显示为单列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14170893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com