0
$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";
$q=mysql_query($query);
//echo $query;
while($e=mysql_fetch_assoc($q))
          $output[]=$e;
   print(json_encode($output));

从这段代码中,它将像这样生成,

[
{"id":"1","latitude":"-77.036519","longitude":"77.036519","elevation":"0","title":"coba","distance":null,"has_detail_webpage":"0","webpage":"0","info":"0"},
{"id":"3","latitude":"12","longitude":"42","elevation":"21","title":"213","distance":"12","has_detail_webpage":"1","webpage":"12","info":"12"},
{"id":"32","latitude":"","longitude":"","elevation":null,"title":null,"distance":null,"has_detail_webpage":"1","webpage":null,"info":null}
]

但我想要这样的东西,

{ "status": "OK", "num_results": 3, "results": 
[ { "id": "2833", "lat": "41.359288",   "lng": "-73.646850", "elevation": "53", "title": "Target4", "distance": "1.756", "has_detail_page": "1", "webpage": "" }, 
  { "id": "2821", "lat": "41.359768", "lng": "-73.646870", "elevation": "0", "title": "Target2", "distance": "1.771", "has_detail_page": "0", "webpage": "" }, 
  { "id": "2829", "lat": "41.359820", "lng": "-73.646870", "elevation": "0", "title": "Target3", "distance": "1.545", "has_detail_page": "1", "webpage": "" } 
] }

我该怎么做?

4

3 回答 3

1

获取所有结果或逐行执行。选择你自己。En 之后创建 json 数组。您可能还想看看您对mysql_ * 函数的使用。因为它们现在已被弃用。你真的应该切换到MySQli / PDO

$result = array();
while($row = mysql_fetch_assoc($q)) {     
 $result[] = $row;
}

$output = array('status' => 'OK' , 'num_results' => count($result), 'results' => $result);
echo json_encode($output);
于 2013-06-30T08:20:26.070 回答
0

要在 json 中添加您希望具有的结构,首先您必须在将其编码为 json 之前从 php 创建该结构。

$objects = array();
while ($r = mysql_fetch_associ($rs) {
      $a = new stdClass();
      $a->status = $r['status'];
      ...
      $a->results = array('id' => $r['id']....)
      $objects[] = $a;
}

echo json_encode($objects);
于 2013-06-30T08:17:21.753 回答
0
$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";

$q=mysql_query($query);
$output = array();
if($q) {
    $output['status'] = 'OK'; 
}
$output['num_results'] = mysql_num_rows($q); 
while($e=mysql_fetch_assoc($q)) {

$output['results'][]= array (
    'id' => $e['id'],
    'lat' => $e['latitude'],
    'lng' => $e['longitude'],
    'elevation' => $e['elevation'],
    'title' => $e['title'],
    'distance' => $e['distance'],
    'has_detail_page' => $e['has_detail_webpage'],
    'webpage' => $e['webpage'],
);
}
print(json_encode($output));
于 2013-06-30T10:07:42.787 回答