How To Convert PHP Array To JSON Object

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

In this article, we will explore the process of converting a PHP array into a JSON object. We'll achieve this transformation by using the json_encode() function, an integral part of PHP that facilitates the conversion of a PHP array or object into a JSON representation.

The need to convert a PHP array into a JSON array is a common requirement in PHP or Laravel applications, particularly when working with AJAX requests. JSON responses are a practical choice for transmitting data due to their ease of use.

Throughout this article, we will present three distinct examples of how to perform this conversion from a PHP array to a JSON object, complete with accompanying output. Additionally, we will discuss how you can forcibly convert the output into a JSON object using the "JSON_FORCE_OBJECT" parameter.

Example 1:

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

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

Output:

["Red","Blue","Green","Yellow","Pink"]

 

 

Example 2:

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

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

Output:

{"0":"Red","1":"Blue","2":"Green","3":"Yellow","4":"Pink"}

 

 

Example 3: 

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

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

Output:

{"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
How To Get Current User Location In Laravel 9
How To Get Current User Locati...

In this article, we will see how to get the current user location in laravel 9. Many times we are required to...

Read More

Mar-23-2022

How To Create Unique Slug In Laravel 9
How To Create Unique Slug In L...

In this article, we will see how to create a unique slug in laravel 9. A slug is the part of a URL that i...

Read More

Sep-27-2022

How to install GCC on Ubuntu 22.04
How to install GCC on Ubuntu 2...

Hello there! If you're diving into the world of programming on Ubuntu 22.04 and want to get your hands dirty with so...

Read More

Jan-15-2024

Jquery appendTo And prependTo Example
Jquery appendTo And prependTo...

In this article we will see jquery appendTo() and prependTo example. The appendTo() method inserts HTML elements at...

Read More

Dec-13-2021