convert Json data to Php Array
How To convert Json data to Php Array
json_decode ( ) - Decode JSON Formatted Data
The json_decode() PHP function converts JSON data to PHP array data.
Parameters
data
The json data that you want to decode in PHP.
dataTypeBoolean
Optional boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth
Optional recursion limit. Use an integer as the value for this parameter.
options
Optional JSON_BIGINT_AS_STRING parameter.
A very simple example:
<?php
$jsonData = '{ "user":"John", "age":22, "country":"United States" }';
$phpArray = json_decode($jsonData);
print_r($phpArray);
foreach ($phpArray as $key => $value) {
echo "<p>$key | $value</p>";
}
?>
OutPut
stdClass Object ( [user] => John [age] => 22 [country] => United States )
user | John
age | 22
country | United States
A more deeply nested JSON data object example:
<?php
$jsonData = '{
"u1":{ "user":"Rahul", "age":22, "country":"India" },
"u2":{ "user":"Kalpesh","age":27, "country":"India" },
"u3":{ "user":"Satish", "age":29, "country":"India" },
"u4":{ "user":"Jitendra", "age":34, "country":"India" }
}';
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) {
echo "<h2>$key</h2>";
foreach ($value as $k => $v) {
echo "$k | $v <br />";
}
}
?>
OutPut:
u1
user | John
age | 22
country | United States
u2
user | Will
age | 27
country | United Kingdom
u3
user | Abiel
age | 19
country | Mexico
An example showing how to call in a .json file and parse it using PHP.
<?php
$jsonData = file_get_contents("mylist.json");
$phpArray = json_decode($jsonData, true);
foreach($phpArray as $key => $value)
{
echo "<h2>$key</h2>";
foreach($value as $k => $v)
{
echo "$k | $v <br />";
}
}
?>
The contents of mylist.json are below, create the file and place on your web server before you attempt to run the script above.
{
"u1":{ "user":"John", "age":22, "country":"United States" },
"u2":{ "user":"Will", "age":27, "country":"United Kingdom" },
"u3":{ "user":"Abiel", "age":19, "country":"Mexico" },
"u4":{ "user":"Rick", "age":34, "country":"Panama" },
"u5":{ "user":"Susan", "age":23, "country":"Germany" },
"u6":{ "user":"Amy", "age":43, "country":"France" }
}
Comments
Post a Comment