sql >> Databasteknik >  >> RDS >> Mysql

Hur skapar man dynamisk matris i php?

Gör city_a-index helt annorlunda från city_b-index så att det är lätt att kontrollera.

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

Visa som en HTML-tabell...

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

Testdata - använd data från @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);

Utdata:

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


  1. Hur man stoppar/startar MySQL med MySQL Workbench

  2. Hur kan jag infoga data i SQL Server med VBNet

  3. Optimerar min mysql-fråga för att använda index för sortering

  4. 3 sätt att ersätta NULL med "N/A" i SQLite