PHP JSON to Array with Example
In this tutorial, you will learn how to decode PHP JSON to array with a detailed explanation. This is a very important feature often used in web development but before getting started, we must know about JSON as mentioned below
What is JSON
JSON is a javascript object notation and text-based format that is used to store data and exchange those data when needed. With the help of JSON, we can send data to the server and get the response from the server in JSON format. JSON can be used in any programming language.
Syntax:
{'object key':object value,'object key1':object value1,'object key2':object value2}
json_decode() function
- 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.
Also read, OOPS concepts in PHP with realtime examples
Below are some of the examples of json_decode
Example 1: to convert the JSON data into a PHP object
<?php
$brothers = '{"Ramen":40,"Robin":37,"Ramesh":31}';
$brothersobj = json_decode($brothers);
print_r($brothersobj); ?>
Output:- stdClass Object ( [Ramen] => 40 [Robin] => 37 [Ramesh] => 31 )