douxiongye5779 2015-08-04 20:06
浏览 98
已采纳

从mysql结果创建数组?

I'm trying to create an array(); from the mysql results/query.

The Array OUTPUT should look exactly like this:

{"1":{"info":"Rooz","lat":51.503363,"lng":-0.127625},
"2":{"info":"Michelle","lat":51.503343,"lng":-0.127567}}

So I tried to do it this:

$sql = "SELECT id, name, lat, lng FROM positions ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
$testLocs = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){

$testLocs[] = $row;

}
print_r(json_encode($testLocs));

but the OUTPUT of the code above is like this:

[{"id":"1","name":"Rooz","lat":"51.5033630","lng":"-0.1276250"},{"id":"2","name":"Michelle","lat":"51.503343","lng":"-0.127567"}]

I have no idea how to achieve the output that I want in an array.

Could someone please advise on this?

any help would be appreciated.

  • 写回答

3条回答 默认 最新

  • dream02008 2015-08-04 20:12
    关注

    Change

    $testLocs[] = $row;
    

    to

    $testLocs[$row["id"]] = array("info"=>$row["name"], "lat"=>$row["lat"], "lng"=>$row["lng"]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 win2012 iscsi ipsec
  • ¥15 封装的 matplotlib animation 不显示图像
  • ¥15 python摄像头画面无法显示
  • ¥15 关于#3d#的问题:d标定算法(语言-python)
  • ¥15 cve,cnnvd漏洞扫描工具推荐
  • ¥15 图像超分real-esrgan网络自己训练模型遇到问题
  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)