PHP JSON to Array with Example

  • This is a built-in PHP function that is used to convert the JSON data into a PHP object or an associative array.
  • This function has a second parameter and if this parameter is set to true then it will return the JSON data into an associative array.

Below are some of the examples of json_decode

<?php 
$brothers = '{"Ramen":40,"Robin":37,"Ramesh":31}';
$brothersobj = json_decode($brothers);
print_r($brothersobj); ?>
<?php 
$brothers = '{"Ramen":40,"Robin":37,"Ramesh":31}';
$brothersobj = json_decode($brothers,true);
print_r($brothersobj);
?>

How to get the values of PHP object from the JSON data

<?php 
$brothers = '{"Ramen":40,"Robin":37,"Ramesh":31}';
$brothersobj = json_decode($brothers);
//print_r($brothersobj);
//Access the decoded values one by one from a PHP object
echo "The value of the first object is: ".$brothersobj->Ramen;
echo "<br>";
echo "The value of the second object is: ".$brothersobj->Robin;
echo "<br>"; echo "The value of the third object is: ".$brothersobj->Ramesh;
?>

How to get the values of associative array from the JSON data

<?php 
$brothers = '{"Ramen":40,"Robin":37,"Ramesh":31}';
$brothersobj = json_decode($brothers,true);
//print_r($brothersobj);
//Access the decoded values one by one from an associative array echo "The value of the first object is: ".$brothersobj['Ramen']; echo "<br>";
echo "The value of the second object is: ".$brothersobj['Robin']; echo "<br>";
echo "The value of the third object is: ".$brothersobj['Ramesh']; ?>

Get the values of PHP object using the foreach loop

<?php 
$brothers = '{"Ramen":40,"Robin":37,"Ramesh":31}';
$brothersobj = json_decode($brothers);
//print_r($brothersobj); echo "<br>";
//Get the values of the object using foreach loop
foreach ($brothersobj as $key => $value)
{
// code...
echo $key .' => '.$value.'<br>';
}
?>

Get the values of the associative array using the foreach loop

<?php 
$brothers = '{"Ramen":40,"Robin":37,"Ramesh":31}';
$brothersobj = json_decode($brothers,true);
echo "<br>";
//Get the values of the object using foreach loop
foreach ($brothersobj as $key => $value)
{
// code...
echo $key . '=> '.$value.'<br>';
}
?>

--

--

Hi, This is Biplab and I am web developer well versed in PHP and other open source technologies. I am here to share my experience with the community.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bipsmedium

Bipsmedium

25 Followers

Hi, This is Biplab and I am web developer well versed in PHP and other open source technologies. I am here to share my experience with the community.