PHP使用方括号语法声明多维数组

时间:2022-02-28 23:10:42

I am trying to create a multi dimensional array using this syntax:

我正在尝试使用以下语法创建多维数组:

$x[1] = 'parent';
$x[1][] = 'child';

I get the error: [] operator not supported for strings because it is evaluating the $x[1] as a string as opposed to returning the array so I can append to it.

我得到错误:[]运算符不支持字符串,因为它将$ x [1]作为字符串进行评估,而不是返回数组,因此我可以追加它。

What is the correct syntax for doing it this way? The overall goal is to create this multidimensional array in an iteration that will append elements to a known index.

这样做的正确语法是什么?总体目标是在迭代中创建这个多维数组,将元素附加到已知索引。

The syntax ${$x[1]}[] does not work either.

语法$ {$ x [1]} []也不起作用。

3 个解决方案

#1


24  

The parent has to be an array!

父母必须是一个阵列!

$x[1] = array();
$x[1][] = 'child';

#2


5  

$x = array();
$x[1] = array();
$x[1][] = 'child';

#3


1  

I think what you want to do is to use $x['parent'] in the end, isn't it ?

我想你想要做的是最后使用$ x ['parent'],不是吗?

So it's not exactly $x = array() but more something like :

所以它不完全是$ x = array()但更像是:

$x = array('parent' => array());
$x['parent'][] = 'child';

#1


24  

The parent has to be an array!

父母必须是一个阵列!

$x[1] = array();
$x[1][] = 'child';

#2


5  

$x = array();
$x[1] = array();
$x[1][] = 'child';

#3


1  

I think what you want to do is to use $x['parent'] in the end, isn't it ?

我想你想要做的是最后使用$ x ['parent'],不是吗?

So it's not exactly $x = array() but more something like :

所以它不完全是$ x = array()但更像是:

$x = array('parent' => array());
$x['parent'][] = 'child';