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

问题描述 投票:0回答:3

我想用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] =>
)

我做错了什么?

php arrays initialization array-push
3个回答
0
投票

您可以像这样简单地创建它:

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

然后再加上只是说:

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

0
投票

非常简短的答案:

$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.

0
投票

尝试下面的代码:

$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;

Demo

© www.soinside.com 2019 - 2024. All rights reserved.