duancan65665 2019-07-29 06:21
浏览 183
已采纳

如何将php字符串转换为jquery数组?

In php I push coordinates to an array in a loop:

        $lat = $location['lat'];
        $lng = $location['lng'];
        array_push($coordinates, $lat.",".$lng);

I then need those coords as a pair in jQuery.

  var coords = "<?php echo $coordinates; ?>";
  console.log(coords);

The above gives me:

40.836132854296686,8.404270310882566,40.7197406,8.563512299999957,41.36256133817761,2.131976960327165

But since I need them as a pair as I later do:

for (var a = 0; a < coords.length; ++a) {
    var pin = coords[a].split(',');
    var latLng = new google.maps.LatLng(pin[0], pin[1]);

I don't know who to convert that string in a pair array object. I thought of adding [] as a string when I push to array in php but it's very bad.

Basically I am looking for:

["55.695694737568054,37.5904788172536", "41.36256133817761,2.131976960327165", "40.836132854296686, 8.404270310882566", "40.7197406, 8.563512299999957"]

Thought of splitting every second comma in js as per this answer but I'm not sure is the correct way.

  • 写回答

1条回答 默认 最新

  • doujiang1939 2019-07-29 06:24
    关注

    Use JSON

    PHP

    $lat = $location['lat'];
    $lng = $location['lng'];
    array_push($coordinates, [$lat, $lng]);
    

    JS

    var coordsJson = '<?php echo json_encode($coordinates); ?>';
    var coords = JSON.parse(coordsJson)
    console.log(coords);
    // [[40.836132854296686,8.404270310882566],[40.7197406,8.563512299999957]]
    
    for (var a = 0; a < coords.length; ++a) {
        var latLng = new google.maps.LatLng(
            parseFloat(coords[a][0]), 
            parseFloat(coords[a][1])
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 爬知乎登录之后内容加载不出来
  • ¥15 怎么用protues测量通频带
  • ¥15 zepelin使用sparkInterpreter 异常
  • ¥15 paho mqtt 接收不到消息
  • ¥15 函数r关于两个分量y,z方向上的图像,分开画r随y的图像,r随z的图像
  • ¥15 如何用Matlab求Pearcey函数的数值积分?
  • ¥15 一个简单的函数定义问题,输出结果是相反的,怎么回事呢?
  • ¥15 页面加载报错,不知道怎么处理
  • ¥20 vue-draggable-resizable选中状态保持
  • ¥15 flink cdc读取SqlServer2016