【问题标题】:php weird undefined offset errorphp奇怪的未定义偏移错误
【发布时间】:2015-09-03 18:18:27
【问题描述】:

在我的 php 应用程序中,我有以下代码:

try {
    $ordersIngredients[$userIngredient->getId()][$day] += $quantity;
} catch (\Exception $e) {
    ~r(array(
        $ordersIngredients[$userIngredient->getId()],
        $day,
        array_key_exists($day, $ordersIngredients[$userIngredient->getId()]),
        $e->getMessage()
    ));
}

r() 函数打印以下内容:

array(4)
    0   =>  array(4)
        0   =>  0.9
        1   =>  null
        2   =>  null
        3   =>  1
    )
    1   =>  3
    2   =>  true
    3   =>  Notice: Undefined offset: 3
)

考虑到数组的转储和array_key_exists,当偏移量实际存在时,我怎么能在未定义的偏移量上出现错误?

【问题讨论】:

标签: php arrays undefined


【解决方案1】:

这里的问题是您试图追加到数组中不存在的值。

$ordersIngredients[$userIngredient->getId()][$day] += $quantity;

这和写法一样:

$ordersIngredients[$userIngredient->getId()][$day] = 
    $ordersIngredients[$userIngredient->getId()][$day] + $quantity;

所以,发生的事情是 PHP 试图读取索引 3 处的值,但它不能。这就是导致您通知的原因。由于它只是一个通知,PHP 将未定义的索引视为null 并继续前进。然后它将null + $quantity 添加到您的数组中。

完成该行后,它会移至您的错误处理程序,然后移至您的 catch 块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多