Jump to: navigation, search

PHP JSON Convert to Array

From w3cyberlearnings

Contents

PHP JSON to Array

In this tutorial, we uses the json_decode() function to convert JSON data to array. If you want to check whether the JSON data is a valid one, please visit json_last_error() function.

Syntax

Convert JSON data to array, without assign the second parameter, it returns an object not an array.

json_decode($json_data, 1);

OR

(array)json_decode($json_data);

Example 1

<?php
$address = '{
      "street1":"2459 Kub Rd",
      "street2":"apt 3913",
      "city":"Houston",
      "state":"Tx"}';

$array_address = json_decode($address,1);

print_r($array_address);

?>

Output

Array
(
    [street1] => 2459 Kub Rd
    [street2] => apt 3913
    [city] => Houston
    [state] => Tx
)

Example 2

<?php

$name = '[
	    {"name":"John"},
	    {"name":"Mark"},
	    {"name":"Marry"}
	]';

$array_name = json_decode($name,1);

print_r($array_name);

?>

Output


Array
(
    [0] => Array
        (
            [name] => John
        )

    [1] => Array
        (
            [name] => Mark
        )

    [2] => Array
        (
            [name] => Marry
        )

)

Example 3

<?php

$json_st = '{
	"name":"John",
	"age":12,
	"address":{"street":"240 Lake Rd","apt":210}}';

$students = json_decode($json_st, 1);

print_r($students);
?>

Output


Array
(
    [name] => John
    [age] => 12
    [address] => Array
        (
            [street] => 240 Lake Rd
            [apt] => 210
        )

)

Example 4

<?php

$my_profile = '{
		"name": "paul",
		"address": {
			"city": "houston",
		        "state": "tx",
			"apt": "244"
		 },
		"experinece":"php",
		"hobby":{
			"fishing":{"area1":"lake","area2":"sea"},
			"game":{"game1":"angry bird","game2":"angry dog"}
                 }
	}';

$my_array = json_decode($my_profile, true);
print_r($my_array);
?>

Output

Array
(
    [name] => paul
    [address] => Array
        (
            [city] => houston
            [state] => tx
            [apt] => 244
        )

    [experinece] => php
    [hobby] => Array
        (
            [fishing] => Array
                (
                    [area1] => lake
                    [area2] => sea
                )

            [game] => Array
                (
                    [game1] => angry bird
                    [game2] => angry dog
                )

        )

)

Related Links


--PHP JSON Convert to Array-- PHP JSON Convert to Object-- PHP Access JSON Data--

Navigation
Web
SQL
MISC
References