My JSON response seems to have excess keys in it. Any idea why?
Here is an excerpt from the JSON response:
{
"0": "1",
"id": "1",
"1": "XX University",
"name": "XX University",
"2": "http:\/\/ree.com\/images\/xxUniversity.png",
"backgroundImageUrl": "http:\/\/ree.com\/images\/XXUniversityLogo.png",
"3": "http:\/\/ree.com\/images\/xxUniversity.png",
"logoImageUrl": "http:\/\/ree.com\/images\/XXUniversityLogo.png"
},
Here is my PHP code:
$query = "SELECT * from $entity"; //Bad security,for a different question
$results = mysqli_query($con,$query);
//Parse to JSON
$json=array();
while($row=mysqli_fetch_array($results)){
$json[]=$row;
}
//Close connection
mysqli_close($con);
//Encode and send response as JSON (using the entity type as a parameter)
//echo json_encode(array($entity => $json), JSON_FORCE_OBJECT);
echo json_encode(array ($entity =>$json));
Your problem is mysqli_fetch_array
. You want to pass MYSQLI_ASSOC
as a second parameter.
while($row=mysqli_fetch_array($results,MYSQLI_ASSOC)){
$json[]=$row;
}
This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.
By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.
mysqli_fetch_array per default retrieves both numeric and named index.
You have to specify an additional parameters to get only the desired ones.