Laravel PHP 棘手的未定义索引错误

Laravel PHP Tricky Undefined Index Error

我正在用头撞墙试图弄清楚我进入 laravel(版本 5.6.23,我检查过 :( ) 中的这个错误。基本上我正在读取由 [ 创建的关联数组=24=]解码,一次调用返回错误:

Undefined index : Itemprice  //this is the index name

但是我已经将整个 JSON dd() 到控制台并且该索引肯定存在,更不用说它今天早些时候工作了。此外,运行 isset() 或 array_key_exists 都 returns 对那个确切的索引为真,所以即使代码本身也同意它是一个存在的索引。我不知道是什么原因导致错误或从这里去哪里。

这是代码:

 foreach($items['ListOrderItemsResult']['OrderItems'] as $item)
    {
    //this is the problem line below
    $price = $item['ItemPrice']['Amount']; //ItemPrice is problem

    $productname = $item['Title']
    $quantity = $item['QuantityOrdered']; 
    $asin = $item['ASIN'];

    $total = $price * $quantity;
    }

这里是实际数组的 dd(上面是“$item”),删除了一些个人信息

   array:11 [▼
  "QuantityOrdered" => "5"
  "Title" => "Two Pack...."
  "PromotionDiscount" => array:2 
   "IsGift" => "false"
   "ASIN" => "..."
  "SellerSKU" => "..."
  "OrderItemId" => "..."
  "ProductInfo" => array:1 
  "QuantityShipped" => "5"
   "ItemPrice" => array:2 [▼
  "CurrencyCode" => "USD"
   "Amount" => "30000"
   ]
   "ItemTax" => array:2 [▶]
  ]

错误表明 Itemprice 不是有效索引。在您的代码示例中,您编写了 ItemPrice 但错误是引用了您没有引用的地方,请仔细检查您的代码并注意索引区分大小写。

错误不太可能来自您提到的位置,或者索引未在数组的后面部分定义。

如果您不确定是否设置了变量,我建议您执行以下操作

$price = isset($item['ItemPrice']['Amount']) ? $item['ItemPrice']['Amount'] : null;

或shorthand语法

$price = $item['ItemPrice']['Amount'] ?? null;