【问题标题】:Undefined index even though the key is declared即使声明了键,也未定义索引
【发布时间】:2021-02-22 11:27:09
【问题描述】:

我有这个生成多维关联数组的 php 脚本:

<?php
$a=array();
$x = 0;
while($x < 2)
{
    $a["color"] = array();
    if($x == 0)
    {
        $a["color"]["price"] = "25";
    }
    else
    {
        $a["color"]["price"] .= "5";
    }
    $x += 1;
}
print_r($a);

?>

我总是收到Notice: Undefined index: price

我已经在 if 语句中明确定义了price 索引,那为什么会这样呢?

【问题讨论】:

  • $a["color"]["price"] .= "5"; 你正在连接到$a["color"]["price"],它还不存在/不再存在
  • 亲爱的 closevoter 使用错字对齐,OP 没有在键盘上滑动并意外输入 22 个字符:$a["color"] = array();

标签: php arrays loops multidimensional-array concatenation


【解决方案1】:

您正在使用$a["color"] = array(); 在每次迭代中清除price 元素

因此,您没有要连接的 price

也许您认为必须在声明子元素之前声明子数组。这对于数组不是必需的,但对于对象是必需的。这是demo——我已经注释掉了防止错误的代码行。


您可以考虑这个替代 sn-p:(Demo) (Demo2)

$a = [];
for ($x = 0; $x < 2; ++$x) {
    if (!$x) {
        $a["color"]["price"] = "25";
    } else {
        $a["color"]["price"] .= "5";
    }
}
var_export($a);

输出:

array (
  'color' => 
  array (
    'price' => '255',
  ),
)

不过,我必须说,您将价格连接起来而不是相加,我觉得很奇怪。要添加,您只需将. 替换为+

【讨论】:

  • 给我一个 3v4l.org 演示链接,我会看看你的意思。
  • 这是Demo(这不是真正的演示,它只是我的cmets代码)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 2015-01-14
  • 2018-07-19
  • 1970-01-01
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多