How to convert JSON to array in PHP

Convert json to array in php; Through this tutorial, i am going to show you how you can convert json string to array in PHP using json_decode() function.

How to convert JSON to array in PHP

Using the PHP json_decode() function, you can decode or convert a JSON object or json string to array and object in PHP.

Using the php json_decode() function, i will take the following examples:

  • Example 1 – Convert JSON String to PHP array
  • Example 2 – json String to Multidimensional Array PHP
  • Example 3 – json decode and access object value php

Example 1 – Convert JSON String to PHP array

Let’s see the following example to convert json string to array in PHP using json_decode() function; is as follows:

<?php

$jObject = '{"Sam":23,"John":32,"Joe":41,"Elvish":43}';

var_dump(json_decode($jObject, true));
?>

The output of the above given code; is as follows:

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

Example 2 – json String to Multidimensional Array PHP

Let’s see the following example to convert json string to multidimensional array in PHP using json_decode() function; is as follows:

<?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 given code; is as follows:

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

Example 3 – json decode and access object value php

Let’s see the following example to decode json and access it’s object in PHP using json_decode() function; is as follows:

<?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 given code; is as follows:

PHP JSON decode example

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *