我想知道如何在JavaScript中運行的PHP腳本中移除此foreach循環中的尾隨逗號。從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>
這使我得到一個結尾逗號,我已經試過了內爆法和RTRIM方法,但這些都不存在問題似乎工作(我還從來沒有使用過這些功能,所以我可能會做這是錯誤的)
我破滅方法是:
<?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( '可視化', '1',{ '包':[ '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>
這非常有意義,非常感謝(3分鐘以上,直到我可以接受你的回答作爲答案)。 – user1848130
@ user1848130不客氣。 – 2012-11-26 19:26:18