2

I don't know php and JSON i wanted a result like below

How to add array employeelist on my json

 {
"employeeList": [
    {
        "name": "Gretchen Rodriquez",
        "email": "gretchenrodriquez@trasola.com"

    },
    {
        "name": "Sharon Harris",
        "email": "sharonharris@trasola.com"

    },
    {
        "name": "Serrano Haynes",
        "email": "serranohaynes@trasola.com"

    }
               ]
   }

My php code

$sql="SELECT * FROM tbl_retro_example";
$result=mysqli_query($conn, $sql); 
$response=array();
while($row=mysqli_fetch_array($result))
 { 
 array_push($response,array("name"=>$row["name"],"email"=>$row["email"]));
  } 
 echo json_encode($response,JSON_FORCE_OBJECT);

i am getting response like below

{
 "0": {
"name": "jugl",
"email": "jual@gmail.com"
 },
 "1": {
"name": "gond",
"email": "gond@gmail.com"
 },
 "2": {
"name": "kaik",
"email": "kaik@gmail.com"
}
 }

How do i get proper result ?

Annabelle
  • 59
  • 1
  • 9

1 Answers1

1

I think you are not too far from where you need to be. If you are looking to have your results under the employeeList key, I would change how you push the results to your array. Also, when using json_enconde you can just tell PHP which array you want to transform. For such, I would transform your:

array_push($response,array("name"=>$row["name"],"email"=>$row["email"]));

into

$response['employeeList'][] = ["name"=>$row["name"],"email"=>$row["email"]];

And, where you have:

json_encode($response,JSON_FORCE_OBJECT)

You can just do

json_encode($response);

For better output results to check your new json I would use print_r instead of echo

Give it a go and let me know how you find it :)

NOTE: I am always working under the most recent PHP version, so I tend to use [] a lot to declare my arrays. I noticed you use array() in your code example, so I am not sure if you are using an older PHP version. If such is the case and [] is not recognised yet by your version, feel free to replace it with your array declaration instead!

Diogo Santo
  • 769
  • 6
  • 12