4

I'm wondering how I can remove the trailing comma in this foreach loop in my PHP script running inside of 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 as I get a trailing comma, I've tried an implode method and rtrim method but none of those appear to be working (I've also never used those functions so I may be doing it wrong)

My implode method was:

<?php
    $resultstr = array();
    foreach ($bans as $key => $value)
                print"['$key', $value],\n";
  $resultstr = implode(",", $resultstr);
    ?>

My rtrim method was:

  <?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>

4 Answers 4

6

What you should do instead of trimming the string afterwards is not generating the trailing comma at all:

$not_first = false;
foreach ($bans as $key => $value) {
    if ($not_first) {
        print(", ");
    }
    $not_first = true;
    print "['$key', $value]\n";
}
1
  • That makes perfect sense, thanks so much for that (3 more minutes until I can accept your response as the answer.) Nov 26, 2012 at 19:25
4

This could be another approach:

var data = google.visualization.arrayToDataTable(<?php
$table = array(array('Country', 'Blocks'));
foreach($bans as $key => $value) {
    $table[] = array($key, $value);
}
echo json_encode($table);
?>);

I often use json_encode so I don't have to take care of escaping all the values.

0
2

You missed something:

echo rtrim($resultstr, ",");

You could also do:

echo substr($resultstr, 0, -1);
4
  • I just tried both of those at the end of my PHP script, and the script result is still the same when viewing the HTML source of the site, adding compiled source to original question. Nov 26, 2012 at 19:21
  • @user1848130 Try my solution as well, might help.
    – user529758
    Nov 26, 2012 at 19:21
  • Agreed. Definately smarter not have the trailing comma in the first place, also using json_encode as suggested by @vstm is a good idea. Nov 26, 2012 at 19:36
  • i guess implode is way much easier for this approach
    – Ahsan
    Jan 30, 2014 at 21:51
0

You could create an array that contains the [key, value] pieces and then glue them with 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);
?>

Output

['key1', val1],
['key2', val2],
['key3', val3]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.