1

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
  • What does your php data look like? Commented Mar 22, 2010 at 21:53

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

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

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

Comments

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.