如何将php数组的名称和坐标转换为谷歌地图点的javascript数组?
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?
我有一个php数组,其中包含一堆我需要的数据,但具体来说我只需要名称和经度 数组中每个项目的纬度,以便我可以在谷歌地图上显示点。 谷歌地图数组最终需要看起来像这样 p>
var points = [
['test name',37.331689,-122.030731,4]
['test name 2',37.331689,-122.030731,4]
];
code> pre>
将我的php数据放入js数组的最佳方法是什么? p >
div>
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];
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.
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)));