I'm trying to create a json object from MySQL results, but not getting the result I need.
Here is the PHP
$json = array();
$result = mysqli_query ($connection, $query);
echo '[';
while($row = mysqli_fetch_array ($result))
{
echo '{';
echo '"latitude":"'.$row['lat'].'",';
echo '"longitude":"'.$row['lng'].'",';
echo '"icon":'.'"./images/'.$row['busColor'].'.png"';
echo '}';
}
echo ']';
$jsonstring = json_encode($json);
echo $jsonstring;
die();
It outputs this
[{"latitude":"39.976257","longitude":"-83.003464","icon":"./images/pink.png"}][]
But I want this
[{"latitude":"39.976257","longitude":"-83.003464","icon":"./images/pink.png"}]
once I get the result I need to pass the object to a jQuery plugin function if that makes any difference
$.getJSON('myJsonURL, function(myMarkers){
$("#map").goMap({
markers: myMarkers
});
});
Thanks
I guess the correct way to do this would be:
$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))
{
$bus = array(
'latitude' => $row['lat'],
'longitude' => $row['lng'],
'icon' => './images/' . $row['busColor'] . '.png'
);
array_push($json, $bus);
}
$jsonstring = json_encode($json);
echo $jsonstring;
die();
you output your json by hand and then you call json_encode on an empty array() - $json
json_encode() outputs [] on you pass an empty array so your last [] comes from here$jsonstring = json_encode($json);
echo $jsonstring;
Edit: More about json_encode json_encode php manual
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With