2017-02-09 80 views
-2

我使用这个API称为“pollDaddy”, 使用PHP来检索JSON响应..I've遇到一个小嗝..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" 
     } 
    } 
} 
} 
+0

不确定你在问什么 - 遍历答案并提取总数?你问如何操纵PHP中的JSON? –

+0

我到目前为止的队友:$ data-> pdResponse-> demand-> demand [0] - > answers [0] - > answer [0] - > total; 但我如何访问'答案'部分后,每个'答案'是我需要帮助。 –

+0

而不是引用只是答案[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; 
}