使用正确的格式创建索引JSON

时间:2016-07-15 09:28:33

标签: javascript php json getjson

我需要在PHP中创建一个JSON数组,如下所示。 需要使用PHP While循环创建数组。

[{
    "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"
}]

我实现的PHP循环如下所示。

$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++;
}

JS for loop with method

可以读取哪些内容
var jqxhr = $.getJSON(serverUrl, function(data) {

    loadPoisFromJsonData(data);

}

但它似乎无法正常工作

ServerUrl是一个回显JSON的PHP文件。

我需要将JSON读取如下。

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
        };

    }
}

2 个答案:

答案 0 :(得分:1)

将数据添加到数组后,您应该使用json_encode()

locationManager:didUpdateToLocation:fromLocation:

您不需要在JS中再次循环它。结果(poiData)已经是 JSON

$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);

答案 1 :(得分:0)

$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