简体   繁体   中英

Stripping last comma from PHP foreach loop

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>

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";
}

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.

You missed something:

echo rtrim($resultstr, ",");

You could also do:

echo substr($resultstr, 0, -1);

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM