简体   繁体   English

如何获取php数组索引并在javascript中使用它

[英]How to get a php array index and use it in javascript

I have a PHP script that returns a latitude and longitude from the database. 我有一个PHP脚本,可以从数据库返回纬度和经度。

Then I have a Javascript loop that loops according to the number of rows the PHP query returns and populate my data object with the logitude and latitude at a given index. 然后,我有一个Javascript循环,该循环根据PHP查询返回的行数进行循环,并使用给定索引处的对数和纬度填充我的数据对象。 The challenge now is - how do I get the index without hard coding it? 现在的挑战是-如何在不进行硬编码的情况下获取索引?

PHP PHP

$DBhost = 'localhost';
$DBuser = 'root';
$DBpass = '';
$DBname = 'symptoms';

$con = mysqli_connect($DBhost, $DBuser, $DBpass) or die(mysql_error());
mysqli_select_db($con, $DBname);

$query = mysqli_query($con, 'SELECT latitude,longitude FROM markers') or die(mysql_error());

$longArr = array();
$latArr = array();
$count = 0;

while ($row = mysqli_fetch_array($query)) {
    $lat = $row['latitude'];
    $lon = $row['longitude'];

    $latArr[$count] = $lat;
    $longArr[$count] = $lon;

    ++$count;
}

JavaScript JavaScript的

var latArr = [];
var longArr = [];
var markersD = [];
var num = <?php echo $count ?>;

for (var i = 0; i < num; i++) {
  var data = {
    lat: '<?php echo $latArr[1]?>',
    lon: '<?php echo $longArr[1]?>'
  }
  console.log(data);
}

You have to create json object via php 您必须通过php创建json对象

while($row = mysqli_fetch_array($query))
{
    $json[] = array('lat' => $row['latitude'], 'lon' => $row['longitude']);
}
$json_string = json_encode($json);

=== JS === === JS ===

var data = <?php echo json_string; ?>;
console.log(data);

You can put all your coords in one array 您可以将所有坐标放在一个数组中

$coords = array();
while($row = mysqli_fetch_array($query))
{
    $coords[] = array(
        'latitude' => $row['latitude'],
        'longitude' => $row['longitude'],
    )
}

and pass it to the js as a JSON object 并将其作为JSON对象传递给js

var data = <?php echo json_encode($coords) ?>;
console.log(data);

All data you need should be available in the javascript 您需要的所有数据都应该在javascript中可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM