Hugo Harun
Hugo Harun

Reputation: 17

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!

Upvotes: 0

Views: 145

Answers (3)

Orangepill
Orangepill

Reputation: 24645

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.

<?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) ?>;

Upvotes: 2

Raiiy
Raiiy

Reputation: 305

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?>

Upvotes: 0

long.luc
long.luc

Reputation: 1191

In your case, use 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.

Upvotes: 0

Related Questions