Q:

PHP program to decode the JSON string into an associative array

belongs to collection: PHP JSON Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to decode the JSON string into an associative array is given below. The given program is compiled and executed successfully.

<?php
//PHP program to decode the Json string into 
//associative array.
$json = '{"Id1":101,"Id2":102,"Id3":103,"Id4":104}';
$ids = json_decode($json);

foreach ($ids as $key => $value)
{
    print ("Key: " . $key . " Value: " . $value . "<br/>");
}
?>

Output:

Key: Id1 Value: 101
Key: Id2 Value: 102
Key: Id3 Value: 103
Key: Id4 Value: 104

Explanation:

Here, we converted the JSON string into an associative array using library function json_decode() and assigned the result into $ids variable.

foreach($ids as $key => $value) 
{  
    print("Key: ".$key." Value: ".$value."
"); }

Here, we printed the key and values of the associative array using the foreach loop on the webpage.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP program to decode the JSON string into a multi... >>
<< PHP program to demonstrate the json_encode() funct...