How to create nested array json using php?

Member

by jerad , in category: PHP General , 6 months ago

How to create nested array json using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , a month ago

@jerad 

To create a nested array JSON using PHP, you can first create a PHP array and then encode it into a JSON string. Here's an example of how you can create a nested array JSON using PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Create a nested array
$data = array(
    'name' => 'John Doe',
    'age' => 30,
    'address' => array(
        'street' => '123 Main St',
        'city' => 'New York',
        'country' => 'USA'
    ),
    'friends' => array(
        array(
            'name' => 'Alice',
            'age' => 25
        ),
        array(
            'name' => 'Bob',
            'age' => 28
        )
    )
);

// Encode the array into a JSON string
$json = json_encode($data);

// Output the JSON string
echo $json;


In this example, we have created a nested array with keys 'name', 'age', 'address', and 'friends'. The 'address' key has nested array values for 'street', 'city', and 'country'. Similarly, the 'friends' key has an array of arrays for each friend with 'name' and 'age'.


After creating the nested array, we used the json_encode() function in PHP to encode the array into a JSON string. Finally, we printed the JSON string using echo.