How to create nested array json using php?

Member

by jerad , in category: PHP General , a year ago

How to create nested array json using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 10 months 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.

Related Threads:

How to create nested array json using php?
How to update the nested array in json using oracle?
How to save json array in mysql using php?
How to create array from a csv file using php?
How to show nested array of json in html in ember.js?
How to extract keys in a nested json array object in presto?