gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:22:17 26 4
gpt4 key购买 nike

我正在使用 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 一次。

关于javascript - 如何将多个 php 值查询到一个 javascript 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30625132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com