【发布时间】:2018-07-11 03:57:24
【问题描述】:
我想在 PHP 中定义一个新的 2D 数组(以便稍后在循环中填充和访问它),但我有处理它的问题。我浏览了一些文章 (e.g. here),但它仍然对我不起作用。
我的代码是:
$part = array(array());
for ($i=0; $i<4; $i++) {
for ($j=0; $j<3; $j++) {
$part[$i][$j]=3;
}
}
for ($i=0; $i<4; $i++) {
for ($j=0; $j<3; $j++) {
echo "values i=$i, j=$j: $part[$i][$j]\n<br>";
}
}
上面代码的结果是:
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=0, j=0: Array[0]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=0, j=1: Array[1]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=0, j=2: Array[2]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=1, j=0: Array[0]
...
输出中提到的第 43 行是:
echo "values i=$i, j=$j: $part[$i][$j]\n<br>";
我也尝试使用上述文章中代码的一点修改版本,但是结果是一样的:
代码:
$a = array(); // array of columns
for($c=0; $c<5; $c++){
$a[$c] = array(); // array of cells for column $c
for($r=0; $r<3; $r++){
$a[$c][$r] = rand();
echo "$a[$c][$r] \n<br>";
}
}
结果:
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[0]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[1]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[2]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[0]
...
上面提到的第55行是:
echo "$a[$c][$r] \n<br>";
有人可以帮我解决这个问题吗?谢谢。
【问题讨论】: