如何在php中创建动态矩阵? [英] How to create dynamic matrix in php?

查看:62
本文介绍了如何在php中创建动态矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有此表"city":

I have this table "city" in my database:


|id |id_city_a |id_city_b|distance|
|1  |1         | 1   | 0      |
|2  |1         | 2   | 8      |
|3  |1         | 3   | 6      |
|4  |2         | 1   | 8      |
|5  |2         | 2   | 0      |
|6  |2         | 3   | 9      |
|7  |3         | 1   | 6      |
|8  |3         | 2   | 9      |
|9  |3         | 3   | 0      |

我希望最终结果在一个矩阵中,例如:

I want the end result to be in a matrix, such as:

| | 1 | 2 | 3 | | 1 | 0 | 8 | 6 | | 2 | 8 | 0 | 9 | | 3 | 6 | 9 | 0 |

| | 1 | 2 | 3 | | 1 | 0 | 8 | 6 | | 2 | 8 | 0 | 9 | | 3 | 6 | 9 | 0 |

This is my code :

This is my code :

`

如何在php中编写代码?请帮助我.

How do I code it in php? please help me.

推荐答案

使city_a索引与city_b索引完全不同,因此易于检查.

Make city_a index completely different from city_b index so it is easy to check.

// 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表格...

Display as an HTML Table...

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的二手数据

Test data - used data from @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

这篇关于如何在php中创建动态矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆