在php中创建二维矩阵
问题是我必须在 php 中创建一个 2D 矩阵,其中每一行和每一列都必须有一个键。我尝试这样做,但发生的情况是创建了一个与矩阵不同的二维数组。我使用了以下代码:
<代码> $x=$row['start_id'];
$y=$row['dest_id'];
$d=$row['距离'];
$this->map[$x][$y]=$d;
这里的地图是预期的矩阵。此代码的目的是创建一个邻接矩阵,然后用最大距离填充未设置的单元格。上面代码中的 $x、$y 和 $d 来自 mysql 查询的结果。
示例输出:
Array (
[10010012] => Array (
[10010013] => 2
[10010016] => 8
)
[10010016] => Array (
[10010015] => 5
)
[10010013] => Array (
[10010014] => 7
[10010016] => 3
)
[10010014] => Array (
[10010015] => 2
)
)
现在的问题是我无法填充空单元格
例如行键=>[10010012]和列键=>[10010015](无法设置值)
任何帮助表示赞赏。如果可能的话,还提到如何遍历这样的矩阵。
我是一个相对初学者,并已尽力解释我的问题。但如果您发现任何不足之处,请指出。
编辑:矩阵不是方形的。
The thing is I have to create a 2D matrix in php where each row and column must have a key. I tried to do this but what happens is that a 2-D array is created which does not resemble a matrix. I used the following code:
$x=$row['start_id'];
$y=$row['dest_id'];
$d=$row['distance'];
$this->map[$x][$y]=$d;
Here map is the intended matrix. The intention of this code is to create an adjacency matrix and then fill the unset cells with maximum distance. $x, $y and $d in above code are derived from result of a mysql query.
Sample Output:
Array (
[10010012] => Array (
[10010013] => 2
[10010016] => 8
)
[10010016] => Array (
[10010015] => 5
)
[10010013] => Array (
[10010014] => 7
[10010016] => 3
)
[10010014] => Array (
[10010015] => 2
)
)
Now the problem is that I am not able to fill the empty cells
e.g. row key =>[10010012] and column key=>[10010015] (Not able to set value)
Any help is appreciated. If possible also mention how to traverse through such matrices.
I am a relative beginner and have tried my best to explain my problem. However if you find any shortcomings please point them out.
Edit: The matrix is not a square one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
另一方面
,为什么要将所有空/不存在的单元格设置为 MAX_DISTANCE?您可以让地图不完整,只要单元格不存在,您就假定 MAX_DISTANCE 作为其值。
编辑:简单的示例
打印
That would be
On the other hand, why do you want to set all empty/non-existing cell to MAX_DISTANCE? You can leave the map incomplete and whenever a cell does not exist you assume MAX_DISTANCE as its value.
edit: simple example
prints