How to convert JSON object to array in PHP

Data-driven applications involve interconversion of JSON object to array in PHP. That’s why PHP has a JSON extension and supports these conversions natively. In one of our articles, “How to convert array to JSON in PHP,” we have seen JSON in-depth. Here’s a quick review of what we’d learned in that article about JSON.

  • JSON stands for Javascript Object Notation.
  • JSON is a lightweight data interchange format.
  • It is language independent.
  • JSON is self-describing and easy to understand data interchange format.

Before we dive into technicalities, it is necessary to ensure that you know why do we convert JSON object to an array in PHP in the first place?

Why do we convert JSON object to array in PHP?

This question might intrigue you if you’ve not worked with APIs or databases. APIs and databases these days usually return data in the form of JSON string. The primary purpose of calling an API in your PHP application is to request data. For example, developing a movie rating website requires data from an API or database.

In the same context, you need to work with the data after fetching it. Now, think for a moment, which would be more convenient to parse, manipulate, and process? A string or an array? Of course, an array. I won’t go into the why part, else the article will deviate from the intended topic. But this is the exact motivation behind converting a JSON object into an array in PHP.

PHP and JSON

PHP provides some useful functions as a part of its JSON extension. These are default functions that you can use right away without any additional imports and configurations. The two most important functions for interconversion of JSON and arrays in PHP are:

We’ve seen json_encode while converting from array to JSON in PHP. In this article, we will explore how to convert JSON object to array in PHP. The function that we’re going to review and explore is json_decode. So, let’s do that without further ado.

JSON object to array PHP

The json_decode function decodes a JSON object and converts it into an array in PHP.

Description

json_decode takes a JSON encoded string and converts it into a PHP variable.

Function Signature

json_decode( string $json, ?bool $associative = null, int $depth = 512,  int $flags = 0) : mixed

Arguments

  • $json –  The JSON string being decoded
  • $associative 
    • If true, the function returns an associative array.  
    • If false, the function returns an object.
    • If null,  the function return type then depends on the flag  JSON_OBJECT_AS_ARRAY.
  • $depth –  Defines the maximum depth to decode in a JSON string.
  • $flags  –  Constant(s) for altering the behavior of the function. (See note)

Return Type

  • Returns the appropriate PHP type depending on the $associative argument.
  • Returns null if the JSON cannot be decoded or the JSON data is deeper than the nesting limit defined by the $depth argument.

Note

The $flags argument defines certain constants that are needed to alter the behaviour of the encoder. PHP defines a comprehensive list of these constants.

Example – JSON object to array PHP using json_decode

Let’s see an example of how to convert JSON object to array in PHP. Here we have a JSON for a customer order API.

$json =
'
{
   "1":
   {
    "customer_name" : "Samuel",
    "payment_method": "Cash",
    "order_id" : ["AA-121","AA-122","AA-142"]
   },
 
   "2":
   {
    "customer_name" : "Martha",
    "payment_method": "Card",
    "order_id" : ["CC-11","CC-16","BB-172"]
   },
 
   "3":
   {
       "customer_name" : "Jackie",
       "payment_method": "Cash",
       "order_id": ["EE-21","EE-101"]
   }
 
}
';

This JSON string is stored in the $json variable in PHP. Let’s pass this on to the json_decode function.

//Converts JSON to array in PHP
var_dump(json_decode($json,true));

You can see that we have passed true to the $associative argument. As already discussed above, this will make the return type an associative array. Here is the output.

array(3) {
  [1]=>
  array(3) {
    ["customer_name"]=> 
    string(6) "Samuel"  
    ["payment_method"]=>
    string(4) "Cash"
    ["order_id"]=>
    array(3) {
      [0]=>
      string(6) "AA-121"
      [1]=>
      string(6) "AA-122"
      [2]=>
      string(6) "AA-142"
    }
  }
  [2]=>
  array(3) {
    ["customer_name"]=>
    string(6) "Martha"
    ["payment_method"]=>
    string(4) "Card"
    ["order_id"]=>
    array(3) {
      [0]=>
      string(5) "CC-11"
      [1]=>
      string(5) "CC-16"
      [2]=>
      string(6) "BB-172"
    }
  }
  [3]=>
  array(3) {
    ["customer_name"]=>
    string(6) "Jackie"
    ["payment_method"]=>
    string(4) "Cash"
    ["order_id"]=>
    array(2) {
      [0]=>
      string(5) "EE-21"
      [1]=>
      string(6) "EE-101"
    }
  }
}


Perfectly decodes the JSON string to an array. This interconversion is something you’ll be using quite often while integrating an API with your application.

Common mistakes using json_decode

Now you’ve understood how to convert JSON object to array in PHP using json_decode, let’s see some common mistakes using this function.

<?php
 
// The following strings are valid JavaScript but not valid JSON
 
// the KEY and value must be enclosed in double quotes
// single quotes are not valid 
$bad_json = "{ 'name': 'Thomas' }";
var_dump(json_decode($bad_json)); // OUTPUT: null
 
// the key must be enclosed in double quotes
$bad_json = '{ name: "Thomas" }';
var_dump(json_decode($bad_json)); // OUTPUT: null
 
// trailing commas are not allowed
$bad_json = '{ name: "Thomas", }';
var_dump(json_decode($bad_json)); // OUTPUT: null
 
?>

The best way to learn code is to practice it yourself. The code above highlights some common mistakes using json_decode. Try to rectify this code at your end. The comments in the code give a lot of hints.

Conclusion

That’s it for this article. You’ve seen how to convert JSON object to array in PHP. The json_decode is the right function for doing so. You’ve seen its usage as well as some common errors that might occur. Stay tuned for more informative content related to PHP.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

How to convert array to JSON in PHP

2 options to comment out code in PHP

Make an associative array in PHP


Article Categories

Article Tags

© 2022 Confident.Systems