从PHP中的JSON数组中提取特定的键值 [英] Extracting specific key value from JSON array in PHP

查看:1036
本文介绍了从PHP中的JSON数组中提取特定的键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从支付网关(JSON)收到以下响应:

I have the following response from a payment gateway (JSON):

    {
  "response": {
    "token": "ch_lfUYEBK14zotCTykezJkfg",
    "success": true,
    "amount": 400,
    "currency": null,
    "description": "test charge",
    "email": "user@user.com",
    "ip_address": "203.192.1.172",
    "created_at": "2012-06-20T03:10:49Z",
    "status_message": "Success!",
    "error_message": null,
    "card": {
      "token": "card_nytGw7koRg23EEp9NTmz9w",
      "display_number": "XXXX-XXXX-XXXX-0000",
      "scheme": "master",
      "address_line1": "42 Sevenoaks St",
      "address_line2": null,
      "address_city": "Lathlain",
      "address_postcode": "6454",
      "address_state": "WA",
      "address_country": "Australia"
    },
    "transfer": null
  }
}

我正在尝试在if语句中获取success => true部分,如下所示:

I'm trying to get the success => true part in an if statement like so:

<?php
    if($response['success'] == true) {
     // continue transaction
    }
?>

没有任何运气,所以我正在寻求有关如何实现此目标的帮助.能够提取其他键值也将很有用.

Without any luck, so I'm asking for some help on how I achieve this. It would be useful to be able to extract other key values too.

谢谢

推荐答案

之所以不能json_decode($response)是因为$response是一个对象,而不是JSON字符串.

The reason you aren't able to json_decode($response) is because $response is an object, not a JSON string.

Pin-PHP库将根据

The Pin-PHP library will automatically decode all requests for you, as per https://github.com/noetix/pin-php/blob/master/src/Pin/Handler.php#L87

要查看响应是否成功,请使用响应对象作为对象:

To see if the response has been successful, use the response object as an object:

if ($response->response->success) {
    echo "Success!";
} else {
    echo "Failed :(";
}

这篇关于从PHP中的JSON数组中提取特定的键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆