php

Convert Array to JSON in PHP

In this tutorial, we are going to see how to convert an Array to JSON in PHP. We will use an associative array that uses a key/value structure to store the data. These keys will be strings or integers which will be used as indexes to look up the corresponding value in the array.

json_encode() function is used to convert the array to JSON. This function is added since PHP 5. Whatever, you can create more nested arrays as per your needs. You can also create an array of objects with this function.

As in JSON, everything is stored as key/value pair. We will convert this array key/value pair into JSON.
 

Convert Array to JSON in PHP
<?php 
	// Creates a nested array
	$arr = array ( 
		// Each array will be converted into an object
		array( 
		  "name" => "Alex Majory",
		  "email" => "[email protected]",
		  "telephone" => "+1 01.09.94.30.12"
		), 
		array( 
		  "name" => "Emily Miron",
		  "email" => "[email protected]",
		  "telephone" => "+1 04.97.35.65.26"
		), 
		array( 
		  "name" => "Bob Leclerc",
		  "email" => "[email protected]",
		  "telephone" => "+1 03.56.16.29.48"
		) 
	); 
	  
	// Function to convert the array to JSON
	echo json_encode($arr); 
?>

Output:

[{"name":"Alex Majory","email":"[email protected]","telephone":"+1 01.09.94.30.12"},
{"name":"Emily Miron","email":"[email protected]","telephone":"+1 04.97.35.65.26"},
{"name":"Bob Leclerc","email":"[email protected]","telephone":"+1 03.56.16.29.48"}]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *