【问题标题】:Add another array in an array variable using a loop in Javascript使用 Javascript 中的循环在数组变量中添加另一个数组
【发布时间】:2013-09-05 02:09:54
【问题描述】:

This 是我想要完成的(接受的答案)。

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]
];


不同之处在于值存储在数组中。我试过这个:

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


有了这个,地图没有显示。请帮我。谢谢!

【问题讨论】:

  • 我会将它排列成正确的数组形式,然后使用 json_encode。

标签: php javascript arrays google-maps google-maps-api-3


【解决方案1】:

为了确保正确编码生成的 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) ?>;

【讨论】:

    【解决方案2】:

    在你的情况下,使用Array.push

    示例代码:

    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:我还没有测试过这段代码。

    【讨论】:

    • 不要期望示例代码在没有任何调整的情况下工作。你需要自己阅读和理解想法和代码。
    【解决方案3】:

    尝试在循环外声明您的位置变量。示例:

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

    【讨论】:

    • TypeError: Object #&lt;Object&gt; has no method 'push'
    • 抱歉,声明为 var locations = Array();并使用 {} 代替 [] 像:locations.push( {$item->H_NAME;?>, $item->H_LAT;?>, $item->H_LONG;?>, H_ID;?>}, );
    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2018-04-07
    相关资源
    最近更新 更多