I need to create a JSON array in PHP which looks like the following. The array needs to be created with a PHP While loop.
[{
"latitude":"124",
"longitude":"",
"altitude":"87654",
"title":"test3",
"description":"This is a test 3",
"urlidle":"0",
"urlselected":"0"
}, {
"latitude":"1ert",
"longitude":"67",
"altitude":"9",
"title":"tes3456",
"description":"This is a test 123",
"urlidle":"www.demo.blah",
"urlselected":"0demo.blah"
}]
The PHP loop I implemented is like the follows.
$poi=array();
while ($row = $output->fetch_array(MYSQLI_ASSOC)) {
$poi[$x]['latitude'] = $row['lat'];
$poi[$x]['longitude'] = $row['long'];
$poi[$x]['type'] = $row['type'];
$poi[$x]['title'] = $row['title'];
$poi[$x]['description'] = $row['desc'];
$poi[$x]['urlidel'] = $row['url1'];
$poi[$x]['urlselected'] = $row['url2'];
$x++;
}
And Which can be read by the JS for loop with method
var jqxhr = $.getJSON(serverUrl, function(data) {
loadPoisFromJsonData(data);
}
But it doesnt seem to be working
Where the ServerUrl is a PHP file that echoes the JSON.
I need the JSON to be read as the follows.
function loadPoisFromJsonDataFn(poiData) {
for (var i = 0; i < poiData.length; i++) {
var singlePoi = {
"id": poiData[i].id,
"latitude": parseFloat(poiData[i].latitude),
"longitude": parseFloat(poiData[i].longitude),
"altitude": parseFloat(poiData[i].altitude),
"title": poiData[currentPlaceNr].name,
"description": poiData[i].description,
"urlidle": poiData[i].urlidle,
"urlselected": poiData[i].urlselected
};
}
}
You should use json_encode() after the data has been added to the array
$poi=array();
$x = 0;
while ($row = $output->fetch_array(MYSQLI_ASSOC)) {
$poi[$x]['latitude'] = $row['lat'];
$poi[$x]['longitude'] = $row['long'];
$poi[$x]['type'] = $row['type'];
$poi[$x]['title'] = $row['title'];
$poi[$x]['description'] = $row['desc'];
$poi[$x]['urlidel'] = $row['url1'];
$poi[$x]['urlselected'] = $row['url2'];
$x++;
}
print_r($poi);
echo json_encode($poi);
You don't need to loop it again in JS. The result(poiData) is already a JSON
var jqxhr = $.getJSON(serverUrl, function(data) {
console.log(data);
//See it in Firebug, it's already a JSON.
alert( JSON.stringify(data) );
//If you want to see it as string
}
$poi=array();
while ($row = $output->fetch_array(MYSQLI_ASSOC)) {
$poi1 = array();
$poi1['latitude'] = $row['lat'];
$poi1['longitude'] = $row['long'];
$poi1['type'] = $row['type'];
$poi1['title'] = $row['title'];
$poi1['description'] = $row['desc'];
$poi1['urlidel'] = $row['url1'];
$poi1['urlselected'] = $row['url2'];
$x++;
$poi = $poi1
}
echo json_encode($poi);
enter code here