How to create an array for JSON using PHP?

Array: There are three types of array in PHP which are listed below:

  • Indexed arrays
  • Associative arrays
  • Multidimensional arrays

For these purpose we will use associative array that uses a key value type structure for storing data. These key will be a string or an integer which will be used as an index to search the corresponding value in the array.
The json_encode function is used to converts the value of array into JSON. This function is added in from PHP5. Also, you can make more nesting of arrays as per your requirement. You can also create an array of array of objects with this function.
As in JSON, everything is stored as a key value pair we will convert these key-value pair of PHP array to JSON which can be used to send the response from the REST API server.

Below are the examples to convert an array into JSON.
Example-1:



filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create an array that contains another
// array with key value pair
$arr = array (
      
    // Every array will be converted
    // to an object
    array(
        "name" => "Pankaj Singh",
        "age" => "20"
    ),
    array(
        "name" => "Arun Yadav",
        "age" => "21"
    ),
    array(
        "name" => "Apeksha Jaiswal",
        "age" => "20"
    )
);
  
// Function to convert array into JSON
echo json_encode($arr);
  
?>

chevron_right


Output:

[{"name":"Pankaj Singh","age":"20"},
{"name":"Arun Yadav","age":"21"},
{"name":"Apeksha Jaiswal","age":"20"}]

Example-2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Declare two dimensional associative
// array and initilize it
$arr = array (
    "first"=>array(
        "id"=>1,
        "product_name"=>"Doorbell",
        "cost"=>199
    ),
    "second"=>array(
        "id"=>2,
        "product_name"=>"Bottle",
        "cost"=>99
    ),
    "third"=>array(
        "id"=>3,
        "product_name"=>"Washing Machine",
        "cost"=>7999
    )
);
  
// Function to convert array into JSON
echo json_encode($arr);
  
?>

chevron_right


Output:

{"first":{"id":1,"product_name":"Doorbell","cost":199},
"second":{"id":2,"product_name":"Bottle","cost":99},
"third":{"id":3,"product_name":"Washing Machine","cost":7999}}


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.