Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Bagaimana cara membuat matriks dinamis di php?

Jadikan indeks city_a benar-benar berbeda dari indeks city_b sehingga mudah untuk diperiksa.

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

Tampilkan sebagai Tabel 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>';

Data uji - data bekas dari @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);

Keluaran:

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


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Tidak dapat menghapus atau memperbarui baris induk ConstraintViolationException

  2. Tambahkan dan tautkan perpustakaan mysql di cmakelist.txt

  3. Pengguna dan kata sandi mysql yang di-hardcode di Node.js

  4. Bisakah Anda membantu mengubah kueri atau kueri lain untuk mendapatkan hasil yang diharapkan?

  5. Cara menyetel nilai multi pilih dari objek array di yii2 saat memperbarui