php - 在PHP中,从 JSON array 中提取特定的key-value

  显示原文与译文双语对照的内容

我从付款网关( 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


 }


}



我正在尝试获取如这样的success => true 语句中的部分:


<?php


 if($response['success'] == true) {


//continue transaction


 }


?>



如果没有任何问题,我就要求有关如何实现这一点的帮助。 如果能够提取其他键值也是很有用的。

谢谢

时间: 原作者:

更新

你的$response 已经是一个对象,因此这个表达式应该能够工作:


if ($response->response->success == true) {


//etc


}



你是否正在查找解码字符串表示形式的代码? 如果是:


$response = <<<'EOM'


{


"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


 }


}


EOM;



$responseData = json_decode($responseText, true);



if ($responseData['response']['success'] == true) {


//continue transaction


}



原作者:

为什么不只使用一个json对象:


$jsonobject = json_encode($responseText);


$response = $jsonobject->response->success;


if($response === true) {


//code here


}



...