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

如何将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.

图片转代码服务由CSDN问答提供 功能建议

在php中我将坐标推送到循环中的数组:

 <  code> $ lat = $ location ['lat']; 
 $ lng = $ location ['lng']; 
 array_push($ coordinates,$ lat。“,”。$ lng); 
    
 
 

然后我需要在jQuery中将这些坐标作为一对使用。

  var coords =“&lt;?php echo $ coordinates;?&gt  ;“; 
 
 
 
 
 
 
 
 
 
 
 
 
 
控制台。
 
 
 
开头
 
 
 
 
 
 
 
 
 
开头
 
 
 
   
 
 

上面给出了我:

  40.8361  8.404270310882566,40.7197406,8.563512299999957,41.36256133817761,2.131976960327165 
   
 
 

但是因为我后来需要它们作为一对:

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

我不知道在对数组对象中转换该字符串的对象。 当我在php中推送到数组时,我想到将 [] 添加为字符串,但这非常糟糕。

基本上我正在寻找: \ n

  [“55.695694737568054,37.5904788172536”,“41.36256133817761,2.131976960327165”,“40.836132854296686,8.404270310882566”,“40.7197406,8.563512299999957”] 
   
 
 

考虑将js中的每一秒逗号分成根据此答案但是 我不确定是不是正确的方法。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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])
        );
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题