【问题标题】:(PHP) Initialize empty multidimensional array and then fill it(PHP) 初始化空多维数组然后填充
【发布时间】:2019-11-07 12:33:23
【问题描述】:

我想创建一个包含 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] =>
)

我做错了什么?

【问题讨论】:

  • 我假设通过复制代码您重命名了变量?比如$other_matches_name$other_matches_nom。此外,我建议您启用错误报告。这将帮助您调试问题,因为此代码(如给出的那样)将返回错误。该错误应该对您有所帮助,如果没有,请不要害怕寻求帮助!
  • 当我print_r 数组时,我得到了不同的结果。以及一些警告和注意事项。
  • 如果你想使用array_push试试array_push($other_matches_info_array, array('name' => $other_matches_name, 'id' => $other_matches_id, 'work' => $other_matches_work));跨度>
  • 你不需要像这样“初始化”一个多维数组。将其初始化为一个简单的数组,仅此而已。 PHP 将自动创建必要的“维度”,然后您开始分配值,而不会出现任何错误、通知或警告。就变量的初始化而言,你不应该做超过$other_matches_info_array = array();(或$other_matches_info_array = [];)。
  • @TomUdding 是的,这是一个错误,感谢您指出,我编辑了我的消息。

标签: php arrays initialization array-push


【解决方案1】:

非常简短的回答:

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

【讨论】:

    【解决方案2】:

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

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

    以后再补充就说:

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

    【讨论】:

    • 但是如果我一开始没有任何东西可以填写呢?我在示例中放置的变量实际上是从数据库中获取数据的,所以我想首先初始化没有内容的数组...
    • 在代码开头声明空数组,然后从数据库中获取记录,然后使用 for / foreach 循环,您可以创建多维数组。
    【解决方案3】:

    试试下面的代码:

    $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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      相关资源
      最近更新 更多