JSON解码,Parse JSON响应和整数值的Undefined Index

时间:2017-01-12 16:45:05

标签: php arrays json laravel amazon-product-api

很奇怪,我已经在这上面工作了三天,在网上寻找解决方案并做出我自己的改变,但仍然没有运气。我正在尝试使用Laravel将这些亚马逊产品检索到我的网站,以及来自JoeDawson/amazon-ecs的这个精彩包裹。 当我从控制器执行命令时,如下所示:

$results = Amazon::search('tv')->json();
dd($results)

我可以看到来自亚马逊的所有数据:

array:2 [
  "OperationRequest" => array:4 [
    ...
  ]
  "Items" => array:5 [
    ...
    "Item" => array:10 [
      ...
      "ItemAttributes" => array:22 [
          "Binding" => "Electronics"
          "Brand" => "LG Electronics"
          "Color" => "Black"
          "EAN" => "8806087769050"
          "EANList" => array:1 [
            "EANListElement" => "8806087769050"
          ]
          "Feature" => array:4 [
            0 => "High dynamic contrast ratio (5M:1) - richer colors, deeper blacks and greater depth of image"
            1 => "Gaming and cinema modes - dedicated features to optimise viewing experiences"
            2 => "USB AutoRun - media content from USB stick runs automatically as soon as TV is switched on"
            3 => "Detachable base - easy way to wall mount your TV and enjoy a viewing experience while saving space"
          ]
          "ItemDimensions" => array:4 [
            "Height" => "226"
            "Length" => "1560"
            "Weight" => "948"
            "Width" => "2526"
          ]
          "Label" => "LG"
          "ListPrice" => array:3 [
            "Amount" => "19999"
            "CurrencyCode" => "GBP"
            "FormattedPrice" => "£199.99"
          ]
      ]
    ]
  ]
]

或者整个结果在这里:http://pastebin.com/TGFgCbAz

在我看来,我可以访问除ListPrice内的值以外的所有值,这会返回“未定义的索引”

@foreach ($results['Items']['Item'] as $amazon)
 {{ $amazon['ItemAttributes']['Title'] }} //returns true with the value
 {{ $amazon['ItemAttributes']['ListPrice']['FormattedPrice'] }} //returns Undefined index: ListPrice
@endforeach

我在控制器端尝试了同样的事情:

foreach ($amazon_results['Items']['Item'] as $amazon) {
        print_r($amazon['ItemAttributes']['ListPrice']['FormattedPrice']);
    }

首先返回FormattedPrice的值,然后抛出相同的错误。

  

£199.99£34.99£194.50哎呀,看起来出了问题。

     

HomeController.php中的1/1 ErrorException第24行:未定义的索引:   ListPrice

为什么我无法获得此值?

1 个答案:

答案 0 :(得分:1)

讨厌成为坏消息的承载者,但简单地说,所有项目都没有ListPrice数组。您提供的完整转储有十个项目。其中两个(索引7和索引9)不包含ListPrice数组。我建议先检查以确定它是否存在:

@foreach ($results['Items']['Item'] as $amazon)
 {{ $amazon['ItemAttributes']['Title'] }}
 @if (array_key_exists('ListPrice', $amazon['ItemAttributes']))
  {{ $amazon['ItemAttributes']['ListPrice']['FormattedPrice'] }}
 @else
  No list price
 @endif
@endforeach