PHP json_decode() | How to decode json to array in PHP

In this tutorial, we will take examples using the json_decode() function. Like, convert JSON string to array PHP, convert JSON string to multidimensional array PHP and JSON decode and access object value PHP.

PHP: json_decode() | How to decode json to array in PHP

Defination: The PHP json_decode() function, which is used to decode or convert a JSON object to a PHP object.

Syntax:

The syntax of JSON decode function is:

json_decode(string, assoc, depth=500, options)

Parameters of json_decode() function

  • json: It holds the JSON string which need to be decode. It only works with UTF-8 encoded strings.
  • assoc: It is a boolean variable. If it is true then objects returned will be converted into associative arrays.
  • depth: It states the recursion depth specified by user.
  • options: It includes bitmask of JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING,, JSON_THROW_ON_ERROR.

Ex 1 – Convert JSON String to PHP array

Let’s take the first example, here we will convert the JSON string to PHP array using the json_decode() function. See the example below:

<?php
 
$jObject = '{"Sam":23,"John":32,"Joe":41,"Elvish":43}';
 
var_dump(json_decode($jObject, true));
?>

The output of the above code is:

Array ( [Sam] => 23 [John] => 32 [Joe] => 41 [Elvish] =>43)

Ex 2 – json String to Multidimensional Array PHP

Let’s take the second example of json_decode() function, Here we will take to convert json multiple objects to a multidimensional array in PHP. Let’s see example:

<?php
 
$jObject = '[
    {
        "title": "PHP",
        "category": "PHP"
    },
    {
        "title": "JSON PHP",
        "category": "PHP"
    },
    {
        "title": "JSON string to array php",
        "category": "php"
    }
]';
//json_decode multidimensional array php
print_r(json_decode($jObject, true));
?>

The output of the above code is:

Array ( 
   [0] => Array ( [title] => PHP [category] => PHP ) 
   [1] => Array ( [title] => JSON PHP [category] => PHP ) 
   [2] => Array ( [title] => JSON string to array php [category] => php ) 
 ) 

Ex 3 – json decode and access object value php

Let’s take third example, in this example we will decode the json object first and after access the value by key. Let’s see the example:

<?php
 
$jsonObject= '{
    "title": "PHP JSON decode example",
    "category": "PHP"
}';
 
 
$res = json_decode($jsonObject);
 
// access title of reponse object
echo $res->title;
 
?>

The output of the above code is:

” PHP JSON decode example"

One thought on “PHP json_decode() | How to decode json to array in PHP

Leave a Reply

Your email address will not be published.