sql >> Database teknologi >  >> RDS >> Mysql

Hvordan opretter man dynamisk matrix i php?

Gør city_a-indekset helt anderledes end city_b-indekset, så det er nemt at tjekke.

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

Vis som en HTML-tabel...

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 - brugte data fra @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);

Output:

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


  1. Fremskynder en (langsom) enorm wordpress-database

  2. Har MySql xml-understøttelse som SQL Server?

  3. 4 måder, lagerdatabaser gavner detailhandlen

  4. Brug af variabel i SQL LIKE-sætning