0

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!

1
  • I'd arrange it into the correct form of arrays and then just use json_encode. Commented Sep 2, 2013 at 3:21

3 Answers 3

2

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

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.

1
  • Don't expect sample code works without any adjustments. You need to read and understand the idea and code by yourself. Commented Sep 2, 2013 at 4:57
0

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?>
2
  • TypeError: Object #<Object> has no method 'push' Commented Sep 2, 2013 at 3:38
  • Sorry, declare like var locations = Array(); And use {} in place of [] like: locations.push( {<?$item->H_NAME;?>, <?$item->H_LAT;?>, <?$item->H_LONG;?>, <?$item->H_ID;?>}, ); Commented Sep 2, 2013 at 3:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.