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

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条