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:
<?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); ?> |
[{"name":"Pankaj Singh","age":"20"},
{"name":"Arun Yadav","age":"21"},
{"name":"Apeksha Jaiswal","age":"20"}]
Example-2:
<?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); ?> |
{"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}}
Recommended Posts:
- How to convert PHP array to JavaScript or JSON ?
- Create a Pandas Series from array
- How to create two dimensional array in JavaScript?
- How to create comma separated list from an array in PHP ?
- Create a comma separated list from an array in JavaScript
- Javascript | JSON PHP
- JSON web token | JWT
- JavaScript | JSON Arrays
- JavaScript | JSON HTML
- How to receive JSON POST with PHP
- Node.js | package.json
- AngularJS | json Filter
- JavaScript | JSON parse() Method
- Export JSON to CSV file in Angular
- Deserializing a JSON into a JavaScript object
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.




