dtvnbe1428 2016-12-06 09:31
浏览 35
已采纳

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

I have a PHP script that returns a latitude and longitude from the database.

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. The challenge now is - how do I get the index without hard coding it?

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

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);
}
  • 写回答

2条回答 默认 最新

  • douxian0008 2016-12-06 09:41
    关注

    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

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

    All data you need should be available in the javascript

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?