How To Create JSON Data In PHP

JSON is used for data exchange in PHP. But how can I create json data in php and pass it to JavaScript?

GOAL

Today’s goal is to generate Json data from PHP array and get the data in JavaScript. This can be used when getting data from the server in PHP and processing the data in JavaScript.

Method

1. Create a nested array data

<?php
$teachers = []
$teachers = [
    "101" => [
        "name" => "Poppins",
        "class" => "music",
    ],
    "102" => [
        "name" => "Dolittle",
        "class" => "natural history",
    ],
    "103" => [
        "name" => "Snape",
        "class" => "pharmacy",
    ],
];
?>

You can create the nested array with for loop, too.

<?php
$teachers = [];
$data_set = [["101", "Poppins", "music"],["102", "Dolittle", "natural history"],["103", "Snape", "pharmacy"]];
for($i=0; $i < count($data_set); $i++){
    $teacher = $teachers_list[$i];
    $teachers += array($teacher[0] => array("name" => $teacher[1], "class" => $teacher[2]));
}
?>

2. Generate Json with json_encode() function

<?php
echo json_encode($teachers);
?>
//output => {"101":{"name":"Poppins","class":"music"},"102":{"name":"Dolittle","class":"natural history"},"103":{"name":"Snape","class":"pharmacy"}}

3. Get the data in JavaScript

Get the json string from the variable $teachers and convert the string to the Object with JSON.parse().

<script type="text/javascript">
    var json_str='<?php echo json_encode($teachers); ?>';
    var json_obj = JSON.parse(json_str);
    console.log(json_str)
    for(k in json_obj){ // get keys
        var teacher = json_obj[k];
        console.log("name: " + teacher['name']);
        console.log("class: " + teacher['class']);
    }
/*
--console output--
name: Poppins
class: music
name: Dolittle
class: natural history
name: Snape
class: pharmacy
*/
</script>

Source Code

The Completed Code is as below.

<?php
$teachers = [];
$teachers = [
    "101" => [
        "name" => "Poppins",
        "class" => "music",
    ],
    "102" => [
        "name" => "Dolittle",
        "class" => "natural history",
    ],
    "103" => [
        "name" => "Snape",
        "class" => "pharmacy",
    ],
];
?>

<script type="text/javascript">
    var json_str='<?php echo json_encode($teachers); ?>';
    var json_obj = JSON.parse(json_str);
    console.log(json_str)
    for(i in json_obj){
        var teacher = json_obj[i];
        console.log("name: " + teacher['name']);
        console.log("class: " + teacher['class']);
    }
</script>