如何将多个 php 值查询到一个 javascript 变量中
How to query multiple php values into a javascript variable
我正在使用 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
它!
我正在使用 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
它!