(PHP) 初始化空的多维数组然后填充它
(PHP) Initialize empty multidimensional array and then fill it
我想创建一个包含 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;
我想创建一个包含 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;