views:

86

answers:

3

I have a php array that has a bunch of data that I need but specifically I need just the name and longitude and latitude from each item in the array so that I can display points on a google map. The google map array needs to look like this in the end

var points = [
['test name', 37.331689, -122.030731, 4]
  ['test name 2', 37.331689, -122.030731, 4]
];

What is the best way to put my php data into a js array?

+1  A: 

A simple means of passing this into JavaScript would simply be to write out the array in the page via json_encode

For example:

<?php
    $sourceArray = array('Test', 'Array', 'With', 'Strings');
    echo '<script type="text/javascript">';
    echo 'var testArray = '.json_encode($sourceArray).';';
    echo '</script>';
?>

N.B.: I'd not recommend using a series of echos, that's just an example. :-)

The advantage of using json_encode is that irrespective of the shape of your array, it should make it intact into JavaScript.

middaparka
A: 

Maybe something like this. Hard to say without knowing how your php array looks.

foreach ($phpData as $key => $val)
{
    $points[] = "['{$val['name']}', {$val['lat']}, {$val['long']}, {$val['zoom']}]";
}
$output = join ("," , $points);
echo "var points = [$output];
Byron Whitlock
Hey I think this is working, but now im just having some trouble actually getting this to work and show up in my javascript, is there something special I need to do to echo out php in javascript?
princyp
A: 

I suggest to use the function json_encode (see the manual page), that returns the json representation of your php var.

To have your javascript code then yo could write:

 echo "var points =" . 
    json_encode( array(array('test name', 37.331689, -122.030731, 4), 
                       array('test name', 37.331689, -122.030731, 4)));
Nicolò Martini