How To Convert PHP Array To JSON Object

    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.

<?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:

Bình luận
Vui lòng đăng nhập để bình luận
Một số bài viết liên quan