dourukeng5302 2015-05-12 17:30
浏览 48
已采纳

PHP将数据转换为json数组

I'm trying to get the coordinates from my database and show them as markers on a map using the Jvectormap plugin. But how can I turn the data which I retrieve from my database into a working json array? I've done something similar before with the morrisJs plugin so I know how to encode them to json but I'm having some issues.

As of now my code looks like this:

$sql = "SELECT latitude, longtitude, user_name FROM page_load 
INNER JOIN users ON page_load.username = users.user_ID
WHERE bot = 0 AND latitude <> 0 AND longtitude <> 0 LIMIT 10";
$sth = $conn->prepare($sql);
$sth->execute();
$arr = array();
while ($rows = $sth->fetchAll(PDO::FETCH_ASSOC)) {
    $arr = $rows;
}    
foreach($arr as $row){
    $temp = $row['latitude'].", ".$row['longtitude'];
    $temp2 = $row['user_name'];
    $newarray = array("latLng" => $temp,
        "name" => $temp2
        );  
}
?>
markers: <?php print_r(json_encode($newarray)); ?>

This returns

{"latLng":"52.5, 6","name":"crecket"},

But I need it to look like this according to the guide for this plugin:

{latLng: [52.5, 6], name: 'crecket'},

As you can see I already turned the 2 langtitude and longtitude variables into 1 key for the array but I can't seem to get rid of the quotations.

So my question really is, what steps do I need to take to turn the result I get now into the format I need?

  • 写回答

1条回答 默认 最新

  • dtgr6303 2015-05-12 17:31
    关注

    Just make $temp an array:

    $temp = array($row['latitude'], $row['longtitude']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化