如何查询多个php值到一个javascript变量

How to query multiple php values into a javascript variable

本文关键字:一个 javascript 变量 php 查询 何查询      更新时间:2023-09-26

我使用php while语句查询纬度和经度坐标到javascript变量。到目前为止,它被查询到单独的js变量,如

  var locations = [
     [ "59.911968", "10.709821" ]
                  ];
  var locations = [
     [ "57.701476", "11.97373" ]
                  ];

但我想让它像

   var locations = [
     [ "59.911968", "10.709821" ]
     [ "57.701476", "11.97373" ]
                  ];
while语句:
<?php
   $args = array('post_type' => 'events');
   $my_query = new WP_Query($args);
        while ($my_query->have_posts()) : $my_query->the_post();  
            $lat  = get_field( "gp_latitude" ); 
            $lon  = get_field( "gp_longitude" ); 
?>
<script>
    var locations = [
     [ <?php echo json_encode($lat) ?>, <?php echo json_encode($lon) ?> ]
    ];
</script>
<?php endwhile; ?>

json_encode支持复数值,您可以:

<?php
   $args = array('post_type' => 'events');
   $my_query = new WP_Query($args);
        locations = array();
        while ($my_query->have_posts()) : $my_query->the_post();
            $locations[] = array(
                "lat" => get_field( "gp_latitude" ),
                "lng" => get_field( "gp_longitude" ),
            );
endwhile; ?>
<script>
    var locations = <?php echo json_encode($locations) ?>;
</script>

我可能把while循环语法弄乱了。这个想法是,你收集$locations中的所有值,然后将其导出到JavaScript一次。

您要声明var locations = []不在循环中,并且在push之后的每个位置都指向数组,如:

locations.push([ <?php echo json_encode($lat) ?>, <?php echo json_encode($lon) ?> ]);

或者更容易创建locations作为php数组和json_encode它!