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']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题