Decoding JSON Arrays with PHP

Category: PHP Programming Tags: ,
September 21, 2011

Decoding JSON Arrays with PHP

JSON is a very popular data format. Although it is simple in scope it can sometimes be confusing to decode in PHP. I think this is because it decodes as object and/or arrays in PHP, so here’s an example that you may like to follow to see how it’s done.

Let’s make some JSON data. This is part of my quiz game and describes the question set and then gives an array of questions, with the answer plus four multiple choice selections (ABCD). To keep it simple, I’ve only got two questions in this set.

"SetName": "UK General Knowledge",
"Ask":"Who wrote \'Lord of the Rings\'?",
"A":"J R R Tolkien",
"B":"C S Lewis",
"C":"Lewis Carroll",
"D":"Issac Asimov"
"Ask":"A \'Blue Brindle\' is a type of what?",
"B":"semi-precious stone",
"D":"House brick"

Notice how we have key-data pairs seperated by colons. The questions are an array and it starts and ends with square brackets (‘[‘ and ‘]’).

PHP has a built in function to decode JSON (surprisingly called ‘json_decode’) and we just pass it the raw JSON string:

$jsonDecodedData = json_decode($jsonQuestionSet);

PHP works really well with JSON as there are similarities on how data is presented and used. Try this and compare how JSON uses ‘:’ where PHP uses ‘=>’:

echo "<pre>";
var_dump( $jsonDecodedData );
echo "</pre>";


which gives:

object(stdClass)#16 (4) {
 ["SetNumber"]=> string(5) "P0002"
 ["SetName"]=> string(20) "UK General Knowledge"
 ["TotalQuestions"]=> int(2)
 array(2) {
 object(stdClass)#15 (6) {
 ["Ask"]=> string(30) "Who wrote 'Lord of the Rings'?"
 ["Answer"]=> string(1) "A"
 ["A"]=> string(13) "J R R Tolkien"
 ["B"]=> string(9) "C S Lewis"
 ["C"]=> string(13) "Lewis Carroll"
 ["D"]=> string(12) "Issac Asimov"
 object(stdClass)#18 (6) {
 ["Ask"]=> string(35) "A 'Blue Brindle' is a type of what?"
 ["Answer"]=> string(1) "D"
 ["A"]=> string(4) "Moth"
 ["B"]=> string(19) "semi-precious stone"
 ["C"]=> string(9) "Butterfly"
 ["D"]=> string(11) "House brick"

And you would use this as:

$s = "Set Number: " .$jsonDecodedData->SetNumber . "<br>";
$s .= "Set Name: " .$jsonDecodedData->SetName . "<br>";
$s .= "Number of Questions: " .$jsonDecodedData->TotalQuestions . "<br>";
$s .=$jsonDecodedData->Question[0]->Ask . "<br>";
$s .=$jsonDecodedData->Question[0]->A . "<br>";
$s .=$jsonDecodedData->Question[1]->Ask . "<br>";
$s .= "answer is ".$jsonDecodedData->Question[1]->{$jsonDecodedData->Question[1]->Answer}
. "<br>";
echo $s;


to output:

Set Number: P0002
Set Name: UK General Knowledge
Number of Questions: 2
Who wrote 'Lord of the Rings'?
J R R Tolkien
A 'Blue Brindle' is a type of what?
answer is House brick