如何在PHP中工作(创建和访问)空的2D数组

时间:2018-01-31 22:15:59

标签: php arrays

我想在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>";

有人可以帮我解决这个问题吗?感谢。

1 个答案:

答案 0 :(得分:2)

在字符串插值中使用“复杂”表达式时需要使用大括号,即

    echo "values i=$i, j=$j: {$part[$i][$j]}\n<br>";

请注意{ ... }部分周围的$part[$i][$j]

只要表达式不是普通的变量名,它就变得“复杂”。

参见PHP manual on simple string interpolation syntaxcomplex syntax

请注意,复杂语法也可用于普通变量,即您可以使用{$i} ... {$j}来保持一致性。

相关问题