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.
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"]
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"}
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:
In this article, we will see how to import and export Excel & CSV files in laravel 10. Here, we will learn about lar...
Mar-08-2023
This article will show the laravel 9 react js crud operation example. Here, we will learn how to create crud operation i...
Dec-08-2022
In this article, we will see how file uploads in react js. File uploading means a user from a client machine wants...
Sep-05-2022
Today we will learn how to remove elements from javascript array, you can use diffrents javascript array...
Apr-07-2021