我正试图在Google的Geochart上绘制一些城市。这个功能非常好,可以绘制城市。
function drawMarkersMap() {
var newInfo = google.visualization.arrayToDataTable([
['City'],
['San Diego'],
['Los Angeles'],
['San Jose']
]);
虽然这很好,所有,我通过PHP从我的数据库生成我的城市。所以,让我们说我们有这个php数组
<?php $city = array("San Diego", "Los Angeles", "San Jose"); ?>
现在,我正在努力解决这个问题。我似乎无法使循环正常工作,以便我可以单独输出每个城市。
当我这样做时,只会显示阵列中的第一个城市(圣地亚哥),我明白为什么......我只是表明这种方法至少会打印“某些东西”
function drawMarkersMap() {
var newInfo = google.visualization.arrayToDataTable([
['City'],
['<?php foreach($city as $location){ echo json_encode($location); } ?>']
]);
//options here
}
所以,我正在尝试使用javascript循环并打印数组中的每个项目,但我似乎没有正确的逻辑
function drawMarkersMap() {
var newInfo = google.visualization.arrayToDataTable([
['City'],
for(i=0;i<json_encode($city).count;i++){
//some kind of print statement mixing php and javascript. I need help here please!
}
]);
这是整个页面
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Google Visualization API Sample</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<?
$city = array("San Jose","Los Angeles","San Diego");
foreach($city as $key=>$value) {
echo "$value";
}
?>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['geochart']});
function drawMarkersMap() {
var newInfo = google.visualization.arrayToDataTable([
['City'],
['<?php echo json_encode($city); ?>']
]);
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(newInfo, {width: 556, height: 347, displayMode: 'markers', region: 'US-CA', resolution: 'provinces'});
}
google.setOnLoadCallback(drawMarkersMap);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="chart_div"></div>
</body>
</html>
答案 0 :(得分:2)
<?php $city = array(array('City'), array('San Diego'), array('Los Angeles'), array('San Jose')); ?>
var newInfo = google.visualization.arrayToDataTable(<?php echo json_encode($city); ?>);
这将重新创建与原始脚本完全相同的数组结构。
答案 1 :(得分:1)
为什么不使用implode功能?
<script type="text/javascript">
<?php $city = array("San Diego", "Los Angeles", "San Jose"); ?>
function drawMarkersMap() {
var newInfo = google.visualization.arrayToDataTable([
['City'],
['<?php echo implode("'],\n\t\t['",$city) ?>']
]);
}
</script>
将导致
<script type="text/javascript">
function drawMarkersMap() {
var newInfo = google.visualization.arrayToDataTable([
['City'],
['San Diego'],
['Los Angeles'],
['San Jose']]);
}
</script>
根据要求......
<script type="text/javascript">
<?php $city = array("San Diego", "Los Angeles", "San Jose"); ?>
function drawMarkersMap() {
var newInfo = google.visualization.arrayToDataTable([
['City'],
['<?php foreach($city as &$c)$c=htmlspecialchars($c,ENT_QUOTES,'UTF-8'); echo implode("'],\n\t\t['",$city); ?>']
]);
}
</script>
..虽然我同意使用JSON非常实用的事实:)