我试图在PHP中实现两个多维数组的总和,但是,通过使用我真的迷失在我正在管理的两个 m 维数组的索引中。foreach
如何正确访问两个阵列?
function sumaMatriz($matrix1, $matrix2){
echo "<table width=\"200\" border=\"1\">";
foreach($matrix1 as $row1 =>$rValue1){
foreach ($matrix2 as $row2 => $rValue2) {
echo "<tr>";
foreach($rValue1 as $col1 =>$cValue1){
foreach ($rValue2 as $col2 => $cValue2) {
echo "<td>".$cValue1+$cValue2."</td>";
}
}
echo "</tr>";
}
}
echo "</table>";
}
我这样$m1
定义$m2
:
$m1 = array (array (rand(0,100), rand(0,100), rand(0,100)),
array (rand(0,100), rand(0,100), rand(0,100)),
array (rand(0,100), rand(0,100), rand(0,100)),
array (rand(0,100), rand(0,100), rand(0,100))
);
$m2 = array (array (rand(0,100), rand(0,100), rand(0,100)),
array (rand(0,100), rand(0,100), rand(0,100)),
array (rand(0,100), rand(0,100), rand(0,100)),
array (rand(0,100), rand(0,100), rand(0,100))
);
这是我的输出,前两个显示的数组是函数的输入。最后一张表是有问题的,它显示为单行。
所以生成的 HTML 如下:
<html>
<head>
<title>
Novatos del PHP
</title>
</head>
<body> <center>
<h2>Matriz 1</h2><table width="200" border="1"><tr><td>58</td><td>49</td><td>90</td></tr><tr><td>83</td><td>70</td><td>13</td></tr><tr><td>21</td><td>1</td><td>69</td></tr><tr><td>56</td><td>73</td><td>39</td></tr></table><br><h2>Matriz 2</h2><table width="200" border="1"><tr><td>31</td><td>35</td><td>86</td></tr><tr><td>2</td><td>86</td><td>99</td></tr><tr><td>98</td><td>16</td><td>40</td></tr><tr><td>99</td><td>35</td><td>1</td></tr></table><br><h2>Suma de matrices</h2><table width="200" border="1"><tr>31</td>35</td>86</td>31</td>35</td>86</td>31</td>35</td>86</td></tr><tr>2</td>86</td>99</td>2</td>86</td>99</td>2</td>86</td>99</td></tr><tr>98</td>16</td>40</td>98</td>16</td>40</td>98</td>16</td>40</td></tr><tr>99</td>35</td>1</td>99</td>35</td>1</td>99</td>35</td>1</td></tr><tr>31</td>35</td>86</td>31</td>35</td>86</td>31</td>35</td>86</td></tr><tr>2</td>86</td>99</td>2</td>86</td>99</td>2</td>86</td>99</td></tr><tr>98</td>16</td>40</td>98</td>16</td>40</td>98</td>16</td>40</td></tr><tr>99</td>35</td>1</td>99</td>35</td>1</td>99</td>35</td>1</td></tr><tr>31</td>35</td>86</td>31</td>35</td>86</td>31</td>35</td>86</td></tr><tr>2</td>86</td>99</td>2</td>86</td>99</td>2</td>86</td>99</td></tr><tr>98</td>16</td>40</td>98</td>16</td>40</td>98</td>16</td>40</td></tr><tr>99</td>35</td>1</td>99</td>35</td>1</td>99</td>35</td>1</td></tr><tr>31</td>35</td>86</td>31</td>35</td>86</td>31</td>35</td>86</td></tr><tr>2</td>86</td>99</td>2</td>86</td>99</td>2</td>86</td>99</td></tr><tr>98</td>16</td>40</td>98</td>16</td>40</td>98</td>16</td>40</td></tr><tr>99</td>35</td>1</td>99</td>35</td>1</td>99</td>35</td>1</td></tr></table>
</center> </body>
</html>