1

am trying to parse this JSON from a Football API using PHP.

Below is a subset of the JSON output.

Specifically, I am trying to retrieve the “45%” value from the "home" element from the below json.

    $json = '{
    "get": "predictions",
    "parameters": {
        "fixture": "198772"
    },
    "errors": [],
    "results": 1,
    "paging": {
        "current": 1,
        "total": 1
    },
    "response": [{
        "predictions": {
            "winner": {
                "id": 1189,
                "name": "Deportivo Santani",
                "comment": "Win or draw"
            },
            "win_or_draw": true,
            "under_over": "-3.5",
            "goals": {
                "home": "-2.5",
                "away": "-1.5"
            },
            "advice": "Combo Double chance : Deportivo Santani or draw and -3.5 goals",
            "percent": {
                "home": "45%",
                "draw": "45%",
                "away": "10%"
            }
        }
    }]
}';

I have tried the following codes but it does not work

$response = json_decode($json);
echo 'Output: '. $response->response->predictions->percent->home;

The error i am getting is: Warning: Attempt to read property "predictions" on array in C:\xampp\htdocs\xampp\livescore\api-test\predictions.php on line 93

I also tried this but no luck.

echo 'Output: '. $response->response[0]->predictions[0]->percent[0]->home;

appreciate any help or insights I can get.

thanks in advance.

2 Answers 2

4

Whenever you see a [ in a json (or any other) object, it's the start of an array, and to reach a child of that array you have to reference it's index (postition). For what you want, this would do it.

$response = json_decode($json);
echo 'Output: '. $response->response[0]->predictions->percent->home;

"response": [{ shows the beginning of an array, and since there's only one item in the array (starting with {) you can reference it by it's index 0. If there were many items in the array, you could loop over them, like

$response->response.forEach(arrayItem => {
 // arrayItem is the current element in the array you're looping though
})
Sign up to request clarification or add additional context in comments.

1 Comment

addendum: crucial whether you give json_decode the parameter 'true' or 'false' as second parameter, which is named associative. when given true, returned objects are converted into associative arrays, so you'd have to access like $object[0]['myField']
0

You've probably missed that only value of "response" is an array, which has dictionary inside. Try this: $response->response[0]->predictions->percent->home

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.