首页 > 解决方案 > 从 php 中的 json 响应中获取值

问题描述

我是 php 新手。我试图从 json 对象中获取价值。我尝试了很多次,但我未能从 json 中获得价值。我只需要来自 json 数组的“txnToken”。我的代码是

$json = json_decode($data, true);
foreach ($json as $key => $value) {
    foreach ($value as $key1 => $value1) {
           print_r($key1);
           
    }
}

JSON响应是:

{
    "head": {
        "responseTimestamp":"1596640639585",
        "version":"v1",
        "clientId":"WEB",
        "signature":"xxxxxxxxxxxxxxxx"
    },
    "body":{
        "resultInfo":{
            "resultStatus":"S",
            "resultCode":"0000",
            "resultMsg":"Success"
        },
        "txnToken":"xxxxxxxxxxxxx",
        "isPromoCodeValid":false,
        "authenticated":false
    }
}

提前致谢。

标签: phparraysjson

解决方案


我想它应该像这样简单:

$json = json_decode($data, true);
print_r($json['body']['txnToken']);

推荐阅读