PHP program to decode the JSON string into a multi-dimensional array

Here, we are going to learn how to decode the JSON string into a multi-dimensional array in PHP? By Nidhi Last updated : December 19, 2023

Prerequisites

To understand this example, you should have the basic knowledge of the following PHP topics:

Decoding JSON String into a Multi-Dimensional Array

Here, we will convert a JSON string into a multi-dimensional array using the json_decode() function and print the elements of the multi-dimensional array on the webpage.

PHP code to decode the JSON string into a multi-dimensional array

The source code to decode the JSON string into a multi-dimensional array is given below. The given program is compiled and executed successfully.

<?php
//PHP program to decode the Json string into 
//multi-dimensional array.
$json = '[[101,"Amit",5000],[102,"Rahul",7000],[103,"Rohit",8000]]';
$emps = json_decode($json);

for ($i = 0;$i < 3;$i++)
{
    for ($j = 0;$j < 3;$j++)
    {
        print ($emps[$i][$j] . "  ");
    }
    echo "<br/>";
}
?>

Output

101 Amit 5000
102 Rahul 7000
103 Rohit 8000

Explanation

Here, we converted the JSON string into a multi-dimensional array using library function json_decode() and assigned the result into $emps variable.

for ($i = 0; $i < 3; $i++) 
{  
    for ($j = 0; $j < 3; $j++) 
    {  
        print($emps[$i][$j]."  ");  
    }  
    echo "
"; }

Here, we printed the employee records contained in a multi-dimensional array using a foreach loop on the webpage.

PHP JSON Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.