-2

i'm using this API called "pollDaddy", using php to retrieve json responses ..I've come across a little hiccup..

How do you get the total of each answer?

My json 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"
        }
    }
}
}
Jesse de gans
  • 1,432
  • 1
  • 14
  • 27
  • Not sure what you're asking-iterate over the answers and pull out the total? Are you asking how to manipulate JSON in PHP? – Dave Newton Feb 09 '17 at 13:06
  • what i've got so far mate : $data->pdResponse->demands->demand[ 0 ]->answers[0]->answer[0]->total; but how can i access each 'answer' after the 'answers' part is what i need help for. – ابوخلود Feb 09 '17 at 13:12
  • Instead of referencing just answer[0] use a variable. It's just an array. – Dave Newton Feb 09 '17 at 13:21

1 Answers1

0

First we have to decode the json data. so we use json_decode. Then we select the right element and loop through it to get all the anwers

$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;
}
Jesse de gans
  • 1,432
  • 1
  • 14
  • 27