How to Create an Array for JSON Using PHP

admin_img Posted By Bajarangi soft , Posted On 03-12-2020

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.

array for Json using php

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(array
("name"=>"sirisha","age"=>"23"),array("name"=>"swapna","age"=>"25"),array("name"=>"veena","age"=>"17"));

//evary array will be coonverted to an object
echo json_encode($arr);

?>

Example-2:


<?php 

//declare two demenssional associative array
//array and initilize it

$arr=array("first"=>array("id"=>1,"product_name"=>" dell laptop","cost"=>21000),"second"=>array("id"=>2,"product_name"=>"lenovo laptop","cost"=>50000),"third"=>array("id"=>3,"product_name"=>"HP laptop","cost"=>45000));

//every array will be convreted to an object

 echo json_encode($arr);
 ?>

Related Post