【问题标题】:How to echo out a specific value from a json response in PHP如何从 PHP 中的 json 响应中回显特定值
【发布时间】:2015-01-15 09:15:06
【问题描述】:

我想知道从这样的 JSON 响应中获取值的最佳方法是什么?

{
"customer": {
  "link": {
    "url": "https://api.neteller.com/v1/customers/CUS_0d676b4b-0eb8-4d78-af25-e41ab431e325",
    "rel": "customer",
    "method": "GET"
}
},
"transaction": {
  "merchantRefId": "20140203113703",
  "amount": 2500,
  "currency": "EUR",
  "id": "176391453448397",
  "createDate": "2014-02-03T18:50:48Z",
  "updateDate": "2014-02-03T18:50:51Z",
  "status": "Accepted",
  "fees": [
    {
      "feeType": "Service_fee",
      "feeAmount": 71,
      "feeCurrency": "EUR"
    }
]
},
"links": [
  {
    "url": "https://api.neteller.com/v1/payments/176391453448397",
    "rel": "self",
    "method": "GET"
  }
]
}

我已经将响应存储在一个变量中:

$content = json_decode($data['content']);

如何在 PHP 中回显这些值?假设我想要merchantRefId。谢谢!

【问题讨论】:

    标签: php json rest


    【解决方案1】:
    $content = json_decode($data['content'], true);
    echo $content['transaction']['merchantRefId'];
    

    【讨论】:

    • 啊,是的,看来我必须将 json_decode 设置为 true!谢谢!会给+1,但还没有15个代表:(
    • 虽然这个答案是有效的,但只有代码的答案不如带解释的答案有用。见How do I write a good answer?简洁是可以接受的,但更全面的解释更好
    【解决方案2】:

    我在这里测试过:PHP Sandbox

    echo $content->transaction->merchantRefId;

    json_decode() 生成标准类的对象。然后,您可以使用对象表示法来访问该对象的属性。

    或者,您可以使用

    $content = json_decode($data['content'],true);

    你会得到一个关联数组而不是一个对象。然后你就可以通过元素名称来访问它,比如

    echo $content['transaction']['merchantRefId'];

    【讨论】:

      【解决方案3】:

      json_decode() 将构建一个关联数组来映射您的 json,所以如果您这样做了

      echo "<PRE>"; print_r($content);
      

      您将看到它是如何映射到数组的。访问数据类似于

      $merchantRefId = $content['transaction']['merchantRefId'];
      

      使用print_r() 函数检查它是如何映射的,这样您就知道它是如何精确映射的。起初,我举例的方式似乎是正确的。

      【讨论】:

      • json_decode() 不会构建关联数组,除非您使用第二个参数告诉它布尔值 true。请参阅涵盖这两种情况的答案。
      猜你喜欢
      • 1970-01-01
      • 2021-11-22
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 2021-02-04
      • 1970-01-01
      相关资源
      最近更新 更多