PHP Extracting Values from Nested JSON Data in PHP

Learn how to extract and print values from nested JSON data in PHP. This tutorial provides an example of decoding a nested JSON object and accessing its values.

<?php
function printValues($arr) {
    global $count;
    global $values;
    
    if(!is_array($arr)){
        die("ERROR: Input is not an array");
    }
    
    foreach($arr as $key=>$value){
        if(is_array($value)){
            printValues($value);
        } else{
            $values[] = $value;
            $count++;
        }
    }
    
    return array('total' => $count, 'values' => $values);
}
 
$json = '{
    "book": {
        "name": "Harry Potter and the Goblet of Fire",
        "author": "J. K. Rowling",
        "year": 2000,
        "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"],
        "genre": "Fantasy Fiction",
        "price": {
            "paperback": "$10.40", "hardcover": "$20.32", "kindle": "4.11"
        }
    }
}';

$arr = json_decode($json, true);
 
$result = printValues($arr);
echo "<h3>" . $result["total"] . " value(s) found: </h3>";
echo implode("<br>", $result["values"]);
 
echo "<hr>";
 
echo $arr["book"]["author"] . "<br>"; 
echo $arr["book"]["characters"][0] . "<br>";  
echo $arr["book"]["price"]["hardcover"];  
?>