Skip to content
Advertisement

How to create JSON root object with php

My current output of my PHP script looks like this:

[
   {
      "id": "1087",
      "name": "Abhishek Saini",
      "email": "info@gmail.com",
      "gender": "male"
   },
   {
      "id": "1088",
      "name": "Gourav",
      "email": "test@gmail.com",
      "gender": "male"
   }
]

but I want it to have a “users:” root object (or whatever it’s called):

{
   "users": [
      {
         "id": "1087",
         "name": "Abhishek Saini",
         "email": "info@gmail.com",
         "gender": "male"
      },
      {
         "id": "1088",
         "name": "Gourav",
         "email": "test@gmail.com",
         "gender": "male"
      }
   ]
}

I don’t really know how to achieve that because a lot of stuff I saw on the internet looks a lot different from my php script.

I think it is only a small change, I don’t want to re-write my whole script.

This is what my php script looks like:

<?php


    ...

    $conn = new mysqli($servername, $username, $password, $dbName);

    if(!$conn){
        die("Connection Failed. ". mysqli_connect_error());

    }else{
        echo "Connection Succeeded";
    }

    $sql = "SELECT * FROM users";
     $result = $conn->query($sql);


     if ($result->num_rows > 0) {

         $result = $conn->query($sql);
         $result_code .= "found lines - ";
         while($row = $result->fetch_assoc()) {
                                 $json[$row["id"]]                     = $row["id"];
                                 $json[$row["name"]]                     = $row["name"];
                                 $json[$row["email"]]                     = $row["email"];
                                 $json[$row["gender"]]                     = $row["gender"]; 
         }
     } else {
     $result_code .= "no rows in db! - ";
     }
echo json_encode($json);
?>

What line do I have to add so it gives me the “users” root?

Advertisement

Answer

Just wrap your existing data in an associative array:

$json = array('users' => $json);
echo json_encode($json);

Output:

{
    "users": [
        {
            "id": "1087",
            "name": "Abhishek Saini",
            "email": "info@gmail.com",
            "gender": "male"
        },
        {
            "id": "1088",
            "name": "Gourav",
            "email": "test@gmail.com",
            "gender": "male"
        }
    ]
}

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement