doumian3780 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; 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 MATLAB APP 制作出现问题
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
  • ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e
  • ¥15 使用deepspeed训练,发现想要训练的参数没有梯度
  • ¥15 寻找一块做为智能割草机的驱动板(标签-stm32|关键词-m3)
  • ¥15 信息管理系统的查找和排序
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),怎么用读取的电磁传感器信号表示小车所在的位置
  • ¥15 如何解决y_true和y_predict数据类型不匹配的问题(相关搜索:机器学习)
  • ¥15 PB中矩阵文本型数据的总计问题。