php 奇怪的未定义偏移错误

php weird undefined offset error

在我的 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 时实际存在偏移量时,我怎么会出现未定义偏移量的错误?

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

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

这和写一样:

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

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

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