如何在PHP中回显json响应中的特定值

时间:2015-01-15 09:15:06

标签: php json rest

我想知道从这样的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。谢谢!

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

我在这里测试了这个:PHP Sandbox

echo $content->transaction->merchantRefId;

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

或者,您可以使用

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

你将获得一个关联数组而不是一个对象。然后,您将能够通过元素名称(如

)访问它

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

答案 2 :(得分:0)

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

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

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

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

使用print_r()函数检查它的映射方式,以便了解它的确切映射方式。起初,我举例说明的方式似乎是正确的。