2018-06-04 09:21
浏览 61

Laravel PHP Tricky未定义索引错误

I am banging my head against a wall trying to figure out this error im getting in laravel (version 5.6.23, I checked :( ). Basically I'm reading an associative array created by JSONdecode, and one call is returning the error:

Undefined index : Itemprice  //this is the index name

But I've dd()'d the entire JSON to the console and that index certainly exists, not to mention it was working earlier today. Additionally, running isset() or array_key_exists both returns true for that exact index so even the code itself agrees it's an index that exists. I have no idea what is causing the error or where to go from here.

HEre's the code:

 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;

and here is a dd of the actual array (above it is "$item") with some personal details removed

   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 [▶]
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douao8353 2018-06-04 09:26

    The error states that Itemprice isn't a valid index. In your code example you write ItemPrice but the error is referencing a place where you didn't, double check your code and take notice that indexing is case sensitive.

    The error is unlikely to be from the place you mentioned, or the index isn't defined in a later part of your array.

    If you aren't sure if a variable is set, I suggest doing something like the following

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

    or shorthand syntax

    $price = $item['ItemPrice']['Amount'] ?? null; 
    解决 无用
    打赏 举报

相关推荐 更多相似问题