I am wondering how can I remove the trailing comma in this foreach loop in my PHP script running inside javascript.
<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>
This causes a problem when I get the final comma, I tried the implode method and the rtrim method, but none of them work (I also never used these functions so that I could be wrong)
My implode method:
<?php $resultstr = array(); foreach ($bans as $key => $value) print"['$key', $value],\n"; $resultstr = implode(",", $resultstr); ?>
My rtrim method:
<?php $resultstr = array(); foreach ($bans as $key => $value) print"['$key', $value],\n"; echo rtrim($resultstr, ","); ?>
When compiled, it looks like this:
<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>