Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Como criar matriz dinâmica em php?


Torne o índice city_a completamente diferente do índice city_b para que seja fácil de verificar.
// generate a two-dimensional matrix in here
$distMatrix = array();

foreach($tableRows as $cityDist) {
    $from = $cityDist['id_city_a'];
    $to = $cityDist['id_city_b'];
    $dist = $cityDist['distance'];

    $distMatrix[$from][$to] = $dist;
}

Exibir como uma tabela HTML...
echo '<table border="1">';
echo '<tr>';
echo '<td>', '#', '</td>';
foreach(array_keys(current($distMatrix)) as $city_b) { // city_b headings
   echo '<td>', $city_b ,'</td>';
}
echo '</tr>';

foreach(array_keys($distMatrix) as $city_a) { // need the city_a as row index
    echo '<tr>';
    echo '<td>', $city_a, '</td>'; // city_a ad
    foreach(array_keys($distMatrix[$city_a]) as $city_b) { // need the city_b as column index
        echo '<td>', $distMatrix[$city_a][$city_b], '</td>'; // distance from the matrix;
    }
    echo '</tr>';
}
echo '</table>';

Dados de teste - dados usados ​​de @ashkufaraz
// changed the city ids so we can easily see city_a and city_b
$tableRows[0]=array("id"=>1, "id_city_a"=>1, "id_city_b"=>11, "distance"=>0);
$tableRows[1]=array("id"=>2, "id_city_a"=>1, "id_city_b"=>12, "distance"=>8);
$tableRows[2]=array("id"=>3, "id_city_a"=>1, "id_city_b"=>13, "distance"=>6);
$tableRows[3]=array("id"=>4, "id_city_a"=>2, "id_city_b"=>11, "distance"=>8);
$tableRows[4]=array("id"=>5, "id_city_a"=>2, "id_city_b"=>12, "distance"=>0);
$tableRows[5]=array("id"=>6, "id_city_a"=>2, "id_city_b"=>13, "distance"=>9);
$tableRows[6]=array("id"=>7, "id_city_a"=>3, "id_city_b"=>11, "distance"=>6);
$tableRows[7]=array("id"=>8, "id_city_a"=>3, "id_city_b"=>12, "distance"=>9);
$tableRows[8]=array("id"=>9, "id_city_a"=>3, "id_city_b"=>13, "distance"=>0);

Resultado:
#   11  12  13
1   0   8   6
2   8   0   9
3   6   9   0