Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to decode JSON objects in Laravel and apply for each loop on that?
The json_decode() method is a PHP built-in function that helps convert a JSON string into a PHP object or associative array. It takes the input value as a string and returns a readable PHP object or array that can be easily looped through using foreach.
Basic JSON Decoding
Following is an example of the json_decode() method
<?php
$studentobj = '{"Neha":35,"Arbaaz":37,"Rehan":43}';
print_r(json_decode($studentobj));
?>
stdClass Object
(
[Neha] => 35
[Arbaaz] => 37
[Rehan] => 43
)
Looping Through JSON Objects
The JSON object is decoded into a PHP object which can be looped using foreach as shown below
<?php
$studentobj = '{"Neha":35,"Arbaaz":37,"Rehan":43}';
$test = json_decode($studentobj);
foreach($test as $name => $age) {
echo $name . "=" . $age . "<br>";
}
?>
Neha=35 Arbaaz=37 Rehan=43
Nested JSON Data
Let us now try an example with nested JSON data containing arrays of objects
<?php
$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 $key => $value) {
echo "$key - $value<br>";
}
echo "<br>";
}
?>
id - 12 name - Rehaan Khan email - rehaan@gmail.com age - 35 id - 13 name - Arbaaz email - arbaaz@gmail.com age - 30
Decoding to Associative Array
The json_decode() function takes a second parameter as a boolean. If true, it returns an associative array instead of a PHP object
<?php
$studentobj = '{"Neha":35,"Arbaaz":37,"Rehan":43}';
$data = json_decode($studentobj, true);
print_r($data);
echo "<br>";
foreach($data as $name => $age) {
echo "$name - $age<br>";
}
?>
Array
(
[Neha] => 35
[Arbaaz] => 37
[Rehan] => 43
)
Neha - 35
Arbaaz - 37
Rehan - 43
Conclusion
Use json_decode() to convert JSON strings into PHP objects or arrays. The second parameter (true) returns associative arrays, making data easier to manipulate in Laravel applications.
