Convert Array to JSON in PHP

Posted by

We will learn how to translate json objects from an array into a php array in this example. We will create a json string from a php array. Using json_encode, we can transform a JSON object into an associative array in PHP. By using the “JSON_FORCE_OBJECT” argument, we may also forcely transform JSON objects.

In php applications, such as when developing web services, we frequently need to convert php arrays to json arrays. Data must always be sent as a JSON response. Additionally, you must submit a json response when working with an ajax request because doing so will make it simple to retrieve and show data.

This lesson includes an example with a straightforward method for converting a php array’s json object. moreover with php convert json object to associative array and force convert json object. In order for you to use anything you need, here are three examples.

Example 1:

<?php
  
  $languages = ['PHP', 'Java', 'JQuery', '.Net', 'Javascript'];
  
  $languagesJSON = json_encode($languages);
  
  echo $languagesJSON;
  
?>

Output:

["PHP","Java","JQuery",".Net","Javascript"]

Example 2:

<?php
  
  $languages = ['PHP', 'Java', 'JQuery', '.Net', 'Javascript'];
   
  $languagesJSONObject = json_encode($languages, JSON_FORCE_OBJECT);
   
  echo $languagesJSONObject;
    
?>

Output:

{"0":"PHP","1":"Java","2":"JQuery","3":".Net","4":"Javascript"}

Example 3:

<?php
  
  $details = ['name'=>'Hardik', 'website'=>'devopsconsulting.in'];
  
  $jsonDetails = json_encode($details);
  
  echo $jsonDetails;
     
?>

Output:

{"name":"Hardik","website":"devopsconsulting.in"}
0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
1
0
Would love your thoughts, please comment.x
()
x