Create nested JSON object in PHP?

In PHP, you can create nested JSON objects using associative arrays with the json_encode() function. This allows you to build complex data structures that can be easily converted to JSON format.

Creating Nested JSON Structure

Here's how to create a nested JSON object using associative arrays ?

<?php
$data = array(
    "client" => array(
        "build" => "1.0",
        "name" => "MyApp",
        "version" => "1.0"
    ),
    "protocolVersion" => 4,
    "data" => array(
        "distributorId" => "DIST001",
        "distributorPin" => "PIN123",
        "locale" => "en-US"
    )
);

$json = json_encode($data);
echo $json;
?>
{"client":{"build":"1.0","name":"MyApp","version":"1.0"},"protocolVersion":4,"data":{"distributorId":"DIST001","distributorPin":"PIN123","locale":"en-US"}}

Pretty Formatted JSON

To make the JSON output more readable, use the JSON_PRETTY_PRINT flag ?

<?php
$data = array(
    "client" => array(
        "build" => "1.0",
        "name" => "MyApp",
        "version" => "1.0"
    ),
    "protocolVersion" => 4,
    "data" => array(
        "distributorId" => "DIST001",
        "distributorPin" => "PIN123",
        "locale" => "en-US"
    )
);

$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;
?>
{
    "client": {
        "build": "1.0",
        "name": "MyApp",
        "version": "1.0"
    },
    "protocolVersion": 4,
    "data": {
        "distributorId": "DIST001",
        "distributorPin": "PIN123",
        "locale": "en-US"
    }
}

Conclusion

Creating nested JSON objects in PHP is straightforward using associative arrays and json_encode(). Use JSON_PRETTY_PRINT for formatted output when debugging or displaying JSON data.

Updated on: 2026-03-15T08:38:34+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements