How To Convert PHP Array To JSON Object

WebSolutionStuff | Jul-08-2020 | Categories : Laravel PHP

In this article, we will see how to convert a PHP array to a JSON object. We will convert a PHP array into a JSON string using json_encode(). The json_encode() function is an inbuilt function in PHP that is used to convert a PHP array or object into JSON representation.

Many times we require to convert PHP array into JSON array in PHP or laravel application. When you are working with ajax requests at that time you need to send a JSON response because we can get JSON data easily.

Here, I will three different examples of how to convert the PHP array to a JSON object with output. Also, we can force convert JSON objects using the "JSON_FORCE_OBJECT" parameter.

Example 1:

In this example, we will use json_encode() function.

  $colors = ['Red', 'Blue', 'Green', 'Yellow', 'Pink'];
  $colorsJSON = json_encode($colors);
  echo $colorsJSON;





Example 2:

In this example, we will use JSON_FORCE_OBJECT to encode the array object.

  $colors = ['Red', 'Blue', 'Green', 'Yellow', 'Pink'];
  $colorsJSONObject = json_encode($colors, JSON_FORCE_OBJECT);
  echo $colorsJSONObject;





Example 3: 

In this example, we will encode the array key and value.

  $address = ['city'=>'Mumbai', 'place'=>'Taj Hotel'];
  $jsonData = json_encode($address);
  echo $jsonData;


{"city":"Mumbai","place":"Taj Hotel"}

I have added 3 examples for your reference, you can use anyone as per your requirements.


You might also like:

Recommended Post
Featured Post

Follow us
facebooklogo github instagram twitter