我想知道如何在javascript中运行的PHP脚本中删除此foreach循环中的尾随逗号。
<html>
<head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country','Blocks'],
<?php
foreach ($bans as $key => $value)
print"['$key', $value],\n";
?>
]);
var options = {
backgroundColor : '#555555',
colors : ['#FFFF00', '#FF0000']
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
};
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
这会导致一个问题,因为我得到一个尾随逗号,我尝试了一个implode方法和rtrim方法,但没有一个似乎工作(我也从来没有使用过这些函数所以我可能做错了)< / p>
我的内爆方法是:
<?php
$resultstr = array();
foreach ($bans as $key => $value)
print"['$key', $value],\n";
$resultstr = implode(",", $resultstr);
?>
我的rtrim方法是:
<?php
$resultstr = array();
foreach ($bans as $key => $value)
print"['$key', $value],\n";
echo rtrim($resultstr, ",");
?>
编译时看起来像这样:
<html>
google.load('visualization','1',{'packages':['geochart']});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country','Blocks'],
['Japan', 11],
['United States', 45],
['Argentina', 1],
]);
var options = {
backgroundColor : '#555555',
colors : ['#FFFF00', '#FF0000']
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
};
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
答案 0 :(得分:6)
你应该做什么而不是之后修剪字符串根本不会产生尾随逗号:
$not_first = false;
foreach ($bans as $key => $value) {
if ($not_first) {
print(", ");
}
$not_first = true;
print "['$key', $value]\n";
}
答案 1 :(得分:4)
这可能是另一种方法:
var data = google.visualization.arrayToDataTable(<?php
$table = array(array('Country', 'Blocks'));
foreach($bans as $key => $value) {
$table[] = array($key, $value);
}
echo json_encode($table);
?>);
我经常使用json_encode,所以我不必去处理所有的值。
答案 2 :(得分:2)
你错过了什么:
echo rtrim($resultstr, ",");
你也可以这样做:
echo substr($resultstr, 0, -1);
答案 3 :(得分:0)
您可以创建一个包含[key, value]
件的数组,然后用implode
粘贴它们:
<强> PHP 强>
<?php
$arr = array();
$arr['key1'] = 'val1';
$arr['key2'] = 'val2';
$arr['key3'] = 'val3';
function PrepareValues(&$item, $key) {
$item = "['$key', $item]";
}
array_walk_recursive($arr, "PrepareValues");
$resultstr = implode(",\n", $arr);
print($resultstr);
?>
<强>输出强>
['key1', val1],
['key2', val2],
['key3', val3]