【问题标题】:How to convert a php string to jquery array?如何将php字符串转换为jquery数组?
【发布时间】:2019-07-29 06:21:37
【问题描述】:

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

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

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

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

上面给了我:

40.836132854296686,8.404270310882566,40.7197406,8.563512299999957,41.36256133817761,2.131976960327165

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

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

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

基本上我在寻找:

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

考虑将 js 中的每一秒逗号拆分为per this answer,但我不确定是否正确。

【问题讨论】:

    标签: php jquery arrays


    【解决方案1】:

    使用 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])
        );
    }
    

    【讨论】:

    • 如果你想在 Javascript 中处理数组,不要忘记coords = JSON.parse(coords);
    • 它给了我var coords = [["40.836132854296686","8.404270310882566"],["40.7197406","8.563512299999957"],["41.36256133817761","2.131976960327165"]];
    • 给我Uncaught SyntaxError: Unexpected token , in JSON at position 18
    • @rob.m 检查这一行array_push($coordinates, [$lat, $lng]);
    • @User863 不知道为什么错了,我用的是array_push($coordinates, [$lat, $lng]);
    猜你喜欢
    • 2014-05-08
    • 2013-10-20
    • 2021-08-26
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    相关资源
    最近更新 更多