Skip to content
Related Articles

Related Articles

How to create an array for JSON using PHP?
  • Last Updated : 22 Feb, 2019

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);
  
?>
Output:
[{"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);
  
?>
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}}

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :