我想用3种类型的信息创建一个数组:名称,ID和工作。首先,我想对其进行初始化,以便以后可以用变量中包含的数据填充它。
我搜索了如何初始化多维数组,以及如何填充它,这就是我想出的:
$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] =>
)
我做错了什么?
您可以像这样简单地创建它:
$arrayMultiDim = [
[
'id' => 3,
'name' => 'Carmen'
],
[
'id' => 4,
'name' => 'Roberto'
]
];
然后再加上只是说:
$arrayMultiDim[] = ['id' => 5, 'name' => 'Juan'];
非常简短的答案:
$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.
尝试下面的代码:
$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;