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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么