How to decode JSON objects in Laravel and apply for each loop on that?


The json_decode() method is a PHP built-in function, which helps to convert a JSON object into a PHP object. It takes the input value as a string and returns a readable PHP object

Example 1

Following is an example of the json_decode() method −

$studentobj = '{"Neha":35,"Arbaaz":37,"Rehan":43}'; print_r(json_decode($studentobj));

Output

The output of the above code is −

stdClass Object
(
  [Neha] => 35
  [Arbaaz] => 37
  [Rehan] => 43
)

Let us now loop through the final object that we get from json_decode().

Example 2

The JSON object is given as a string to json_decode(). The $test is now an object which can be looped using foreach as shown below −

$studentobj = '{"Neha":35,"Arbaaz":37,"Rehan":43}'; $test = json_decode($studentobj); foreach( $test as $a => $values) { echo $a."=".$values.'<br/>'; }

Output

The output of the above code is −

Neha=35
Arbaaz=37
Rehan=43

Example 3

Let us now try an example with nested data, as shown below −

$Studentdata = '[{ "id":12, "name":"Rehaan Khan", "email":"rehaan@gmail.com", "age": 35 }, { "id":13, "name":"Arbaaz", "email":"arbaaz@gmail.com", "age": 30 }]'; $data = json_decode($Studentdata); foreach($data as $student) { foreach($student as $mykey=>$myValue) { echo "$mykey - $myValue </br>"; } }

Output

The output of the above code is

id - 12
name - Rehaan Khan
email - rehaan@gmail.com
age - 35
id - 13
name - Arbaaz
email - arbaaz@gmail.com
age - 30

Example 4

The json_decode() function takes in the second parameter as a boolean. If true it gives back an associative array instead of a PHP object. Let us try an example for the same.

$studentobj = '{"Neha":35,"Arbaaz":37,"Rehan":43}'; $data = json_decode($studentobj, true); print_r($data); foreach($data as $mykey=>$myValue) { echo "$mykey - $myValue "; }

Output

The output of the above code is −

Array ( [Neha] => 35 [Arbaaz] => 37 [Rehan] => 43 ) Neha - 35
Arbaaz - 37
Rehan - 43 

Updated on: 30-Aug-2022

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements