gpt4 book ai didi

javascript - 从 PHP foreach 循环中去除最后一个逗号

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:59:27 24 4
gpt4 key购买 nike

我想知道如何删除在 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 方法,但这些方法似乎都不起作用(我也从未使用过这些函数,所以我可能做错了)

我的内爆方法是:

<?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', {'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>

最佳答案

你应该做的不是事后 trim 字符串,而是根本不生成尾随逗号:

$not_first = false;
foreach ($bans as $key => $value) {
if ($not_first) {
print(", ");
}
$not_first = true;
print "['$key', $value]\n";
}

关于javascript - 从 PHP foreach 循环中去除最后一个逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13571507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com