sql >> Base de Datos >  >> RDS >> Mysql

MYSQL + PHP para mostrar datos de dos filas como una sola columna

//Primero busqué todos los datos de la base de datos

$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;
}

//luego procesado en php para mostrar como querías

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

Nota:Se recomienda encarecidamente utilizar mysqli_* en lugar de mysql.