(PHP)初始化空的多维数组,然后填充它



我想创建一个包含3种类型信息的数组:name、id和work。首先,我只想初始化它,这样以后就可以用变量中包含的数据填充它。

我搜索了如何初始化多维数组,以及如何填充它,这就是我想到的:

$other_matches_info_array = array(array());
$other_matches_name = "carmen";
$other_matches_id = 3;
$other_matches_work = "SON";
array_push($other_matches_info_array['name'], $other_matches_name);
array_push($other_matches_info_array['id'], $other_matches_id);
array_push($other_matches_info_array['work'], $other_matches_work);

这是我print_r数组时得到的结果:

Array
(
[0] => Array
(
)
[name] =>
)

我做错了什么?

非常简短的回答:

$other_matches_info_array = array();
// or $other_matches_info_array = []; - it's "common" to init arrays like this in php
$other_matches_name = "carmen";
$other_matches_id = 3;
$other_matches_work = "SON";
$other_matches_info_array[] = [ 
'id' => $other_matches_id,
'name' => $other_matches_name
];
// so, this means: new element of $other_matches_info_array = new array that is declared like this.

您可以简单地创建它,如下所示:

$arrayMultiDim = [ 
[
'id' => 3,
'name' => 'Carmen'
],
[
'id' => 4,
'name' => 'Roberto'
]
];

然后稍后添加到只说:

$arrayMultiDim[] = ['id' => 5, 'name' => 'Juan'];

尝试以下代码:

$other_matches_info_array_main = [];
$other_matches_name = "carmen";
$other_matches_id = 3;
$other_matches_work = "SON";
$other_matches_info_array['name'] = $other_matches_name;
$other_matches_info_array['id'] = $other_matches_id;
$other_matches_info_array['work'] = $other_matches_work;

$other_matches_info_array_main[] = $other_matches_info_array;

演示

相关内容

最新更新