PHP program to convert an associated array into JSON format

Here, we are going to learn how to convert an associated array into JSON format in PHP?
Submitted by Nidhi, on November 23, 2020 [Last updated : March 13, 2023]

Associated Array into JSON Format Conversion

Here, we will create an associative array that contains the Id's and we will convert the array into JSON format using json_encode() function.

PHP code to convert an associated array into JSON format

The source code to convert an associated array into JSON format is given below. The given program is compiled and executed successfully.

<?php
//PHP program to convert an associated array
//into JSON format.
$Ids = array(
    'Id1' => 101,
    'Id2' => 102,
    'Id3' => 103,
    'Id4' => 104
);
$jsonStr = json_encode($Ids);
printf("Json String is: %s<br>", $jsonStr);
?>

Output

Json String is: {"Id1":101,"Id2":102,"Id3":103,"Id4":104}

Explanation

Here, we created an associative array that contains the ID numbers. Here, we used library function json_encode() that will convert the associative array into a JSON string and assigned to the variable $jsonStr. After that we printed the $jsonStr on webpage using printf() function.

PHP JSON Programs »





Comments and Discussions!

Load comments ↻





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