简体   繁体   English

使用Javascript中的循环在数组变量中添加另一个数组

[英]Add another array in an array variable using a loop in Javascript

This is what I am trying to accomplish (the accepted answer). 就是我想要完成的(接受的答案)。

var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
];


The difference is the values are stored in an array. 不同之处在于值存储在数组中。 I tried this: 我试过这个:

    <?foreach($nearest_hospitals as $item):?>
    var locations = [
          [<?$item->H_NAME;?>, <?$item->H_LAT;?>, <?$item->H_LONG;?>, <?$item->H_ID;?>],
    ];
    <?endforeach?>


With this, the map is not showing. 有了这个,地图就不显示了。 Please help me. 请帮我。 Thank you! 谢谢!

To ensure proper encoding of the resulting javascript object I would suggest creating a php array of all of your elements then calling json_encode to produce the json. 为了确保生成的javascript对象的正确编码,我建议创建一个包含所有元素的php数组,然后调用json_encode来生成json。

<?php

   $locations = array();
   foreach($nearest_hospitals as $item){
        $locations[] = array($item->H_NAME,$item->H_LAT,$item->H_LONG,$item->H_ID);
   }
?>
var locations = <?= json_encode($locations) ?>;

In your case, use Array.push . 在您的情况下,使用Array.push

Sample code: 示例代码:

var locations = new Array;
<?foreach($nearest_hospitals as $item):?>
    locations.push(
          [<?$item->H_NAME;?>, <?$item->H_LAT;?>, <?$item->H_LONG;?>, <?$item->H_ID;?>]
    );
<?endforeach?>

Ps: I haven't tested this code yet. Ps:我还没有测试过这段代码。

Try to declare your locations variable outside the loop. 尝试在循环外声明您的位置变量。 Example: 例:

var locations = {};
<?foreach($nearest_hospitals as $item):?>
    locations.push(
          [<?$item->H_NAME;?>, <?$item->H_LAT;?>, <?$item->H_LONG;?>, <?$item->H_ID;?>],
    );
<?endforeach?>

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

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