Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i get key in php json data

I managed to get all the data in loops one by one. But I only want to get the 2 questions inside the ‘maths’ object and when I try other methods I get different errors.
Ex: Cannot use object of type stdClass as array

JSON:

{
"quiz": {
    "sport": {
        "q1": {
            "question": "Which one is correct team name in NBA?",
            "options": [
                "New York Bulls",
                "Los Angeles Kings",
                "Golden State Warriros",
                "Huston Rocket"
            ],
            "answer": "Huston Rocket"
        }
    },
    "maths": {
        "q1": {
            "question": "5 + 7 = ?",
            "options": [
                "10",
                "11",
                "12",
                "13"
            ],
            "answer": "12"
        },
        "q2": {
            "question": "12 - 8 = ?",
            "options": [
                "1",
                "2",
                "3",
                "4"
            ],
            "answer": "4"
        }
    }
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PHP Codes:

$jsonFile = json_decode(file_get_contents('example_2.json', true));
function getMathQuestions($jsonFile) {
    foreach($jsonFile as $val) {
        if(is_object($val)) {
            getMathQuestions($val);
        } else {
            if(is_array($val)) {
                getMathQuestions($val);
            } else {
                echo $val . "<br>";
            }
        }
    }
}
echo getMathQuestions($jsonFile);

>Solution :

You are missing json_decode parameter associative, if not specified you will get stdClass object instead of php array of data.

So change line:

$jsonFile = json_decode(file_get_contents('example_2.json', true));

to:

$jsonFile = json_decode(file_get_contents('example_2.json', true), true);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading