php解析一个Json文件

时间:2017-02-09 12:59:13

标签: php json

我正在使用这个名为" pollDaddy"的API, 用php来检索json的回复..我遇到了一点打嗝......

你如何得到每个答案的总数?

我的json数据:

{
"pdResponse": {
    "partnerGUID": "3F2504E0-4F89-11D3-9A0C-0305E82C3301",
    "userCode": "123456-FErKS5yu15scpSGmvip4JA==",
    "demands": {
        "demand": {
            "result": {
                "answers": {
                    "answer": [{
                        "text": "Yes",
                        "id": "23123124",
                        "total": "1074",
                        "percent": "89.13"
                    }, {
                        "text": "No",
                        "id": "23123125",
                        "total": "131",
                        "percent": "10.87"
                    }]
                }, "id": "690432265"
            }, "id": "GetPollResults"
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

首先我们必须解码json数据。所以我们使用json_decode。然后我们选择正确的元素并循环遍历它以获得所有的答案

$data = '{ "pdResponse": { "partnerGUID": "3F2504E0-4F89-11D3-9A0C-0305E82C3301", "userCode": "123456-FErKS5yu15scpSGmvip4JA==", "demands": { "demand": { "result": { "answers": { "answer": [{ "text": "Yes", "id": "23123124", "total": "1074", "percent": "89.13" }, { "text": "No", "id": "23123125", "total": "131", "percent": "10.87" }] }, "id": "690432265" }, "id": "GetPollResults" } } } }';


$response = json_decode($data);
$answers = $response->pdResponse->demands->demand->result->answers->answer;

foreach($answers as $a)
{
    echo $a->total;
}