【问题标题】:Unable to access or parse decoded json structure in PHP无法在 PHP 中访问或解析解码的 json 结构
【发布时间】:2013-06-26 15:11:49
【问题描述】:

我正在尝试访问解码后的 json 结构,其中$encoded 包含来自shopify API GET /admin/orders/450789469.json 的响应(请参阅their docs)。

$decoded= json_decode($encoded_input, true);
var_dump($decoded);

$decoded 的转储显示解码的嵌套数组,但是当我尝试访问单个元素时,什么都没有显示。

echo $decoded->orders[0]->buyer_accepts_marketing; 

谁能解释一下为什么解码后的 json 结构无法访问?谢谢

【问题讨论】:

  • 另外,密钥是order,而不是orders。根据他们的文档。
  • @RocketHazmat 但示例响应显示不同。
  • @MatteoTassinari:什么示例响应?这是他调用的 API:docs.shopify.com/api/order#show

标签: php shopify json


【解决方案1】:

当您使用json_decode() 和“true”作为第二个参数时,所有内容都会变成数组而不是对象。

试试$decoded['orders'][0]['buyer_accepts_marketing']

【讨论】:

    【解决方案2】:

    线

    $decoded= json_decode($encoded_input, true);
    

    告诉 PHP 将字符串解码为数组,然后在行

    $decoded->orders[0]->buyer_accepts_marketing; 
    

    您尝试将其作为对象访问。您可以尝试使用

    $decoded['orders'][0]['buyer_accepts_marketing'];
    

    改为。

    编辑:另见文档:http://www.php.net/manual/en/function.json-decode.php

    编辑 2:根据 api 规范,您应该改为访问

    $decoded['order']['buyer_accepts_marketing'];
    

    【讨论】:

    • 我知道这听起来很奇怪,但就是无法检索元素。这是显示嵌套数组结构的 var_dump($decoded):array(3) { [0]=> array(48) { ["buyer_accepts_marketing"]=> bool(true) ["cancel_reason"]=> NULL [" cancelled_at"]=> NULL ["cart_token"]=> string(32) "be0dc3ae66a4791435394405372fff53
    • 请说明您转储了什么以及如何尝试访问它。
    • 我已将导入的订单转储为 $decoded= json_decode($encoded_input, true); var_dump($decoded);我试图将此结构的元素显示为: $decoded['orders']['buyer_accepts_marketing'];
    • 我可以像 foreach ($decoded['orders'] as $order) { echo "status:". $order['buyer_accepts_marketing'] ."\n"; }; 但是有没有一种方法可以在一个语句中检索单个数组元素?
    • 你试过$order = $decoded['orders'][0]然后echo $order['buyer_accepts_marketing']吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 2017-09-16
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多