sql >> データベース >  >> RDS >> Mysql

PHPで動的マトリックスを作成する方法は?

    city_aインデックスをcity_bインデックスとは完全に異なるものにして、簡単に確認できるようにします。

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

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

    テストデータ-@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);
    

    出力:

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


    1. mysqlデータベースに接続するためのRESTAPIURLを作成します

    2. OracleのCOLLATION()関数

    3. MySQL InnoDB SELECT ... LIMIT 1 FOR UPDATE Vs UPDATE ... LIMIT 1

    4. サブクエリの問題でのOracleSQLの順序付け!