【问题标题】:Building a Multidimensional Array Programmatically以编程方式构建多维数组
【发布时间】:2022-06-10 20:09:39
【问题描述】:

这可能是不可能的,而且我是该死的傻瓜。但是,我正在尝试在 PHP 中构建一个数组,其中一些元素是变量。

$myArr = array();
$i = 1;
$n = 5;
for($i = 1; $i <= $n; $i++) {
  if($i === 1){
      $myArr["k$i"] = array(
          'description' => 'Some special text for the k1 element',
          'type' => 'some type',
          'foo' => 'bar',
      )
  }else{
      $myArr["k$i"] = array(
          'description' => 'This is the number ' . $i . ' element description.'
          'type' => 'some type',
          'foo' => 'bar',
      )
  }
}
return $myArr;

结果应该是:

$myArr = [
  k1 => [
    'description' => 'Some special text for the k1 element',
    'type' => 'some type',
    'foo' => 'bar',
  ],
  k2 => [
    'description' => 'This is the number 2 element description.'
  ...
  ],
] // ending bracket for the $myArr array

PHP 最常抱怨大括号关闭 IF 语句。任何建议将不胜感激。


编辑

查看一些长长的“常见语法错误”列表的建议不是答案,也没有足够具体的答案来及时帮助我。另外,在搜索我的问题的答案时,我根本没有找到该解决方案——也许“常见语法错误”解决方案没有正确标记?

另外,我发布了这个问题,因为我设法找到和审查的许多其他与 PHP 数组相关的问题从未向我展示过如何处理数组内的变量。我用示例代码发布了我的问题,希望未来的编码人员可以找到如何在数组语法中处理变量。

【问题讨论】:

  • 在右大括号之前的两个赋值语句之后缺少分号。
  • 这能回答你的问题吗? PHP parse/syntax errors; and how to solve them
  • @KevinY -- 谢谢。这非常有帮助,我相信这就是 PHP 被挂在 IF 语句的花括号上的原因。我会投票赞成这条评论,但我看不到选项——也许我在 SO 上没有足够的声誉。无论如何,再次感谢。

标签: php arrays


【解决方案1】:

您的代码是正确的,但您忘记了分号和逗号

$myArr = array();
$i = 1;
$n = 5;
for($i = 1; $i <= $n; $i++) {
  if($i === 1){
      $myArr["k$i"] = array(
          'description' => 'Some special text for the k1 element',
          'type' => 'some type',
          'foo' => 'bar',
      );
  }else{
      $myArr["k$i"] = array(
          'description' => 'This is the number ' . $i . ' element description.',
          'type' => 'some type',
          'foo' => 'bar',
      );
  }
}
return $myArr;

【讨论】:

    猜你喜欢
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    相关资源
    最近更新 更多