从循环的最终迭代生成的文本行中删除尾随逗号


Remove trailing comma from line of text generated by final iteration of loop

我正在创建文本行以供应用程序中的另一个层使用。 这些行是:

['Jun 13',529],
['Jul 13',550],
['Aug 13',1005],
['Sep 13',1021],
['Oct 13',1027],

从文本的最后一行中删除尾随逗号的最快/最简单的方法是什么?

我期待这样的事情:

['Jun 13',529],
['Jul 13',550],
['Aug 13',1005],
['Sep 13',1021],
['Oct 13',1027]

实际代码:

$i = 0;
while($graph_data = $con->db_fetch_array($graph_data_rs))
{
    $year = $graph_data['year'];
    $month = $graph_data['month'];
    $count = $graph_data['count'];
    $total_count = $graph_data['total_count'];
    // for get last 2 digits of year
    $shortYear = substr($year, -2, 2);
    // for get month name in Jan,Feb format
    $timestamp = mktime(0, 0, 0, $month, 1);
    $monthName = date('M', $timestamp );
    
    $data1 = "['".$monthName.' '.$shortYear."',".$total_count."],";
    $i++;
}
  • 如果你在变量中有该数组并且想要一个字符串,你可以使用 implode 来获取一个由胶水字符分隔的字符串。
  • 如果已有字符串,则可以使用 rtrim 删除字符串右侧的最后一个字符。
  • 如果你有一个数组,其中的值是一个字符串['Oct 13',1027](以逗号结尾),你有上面的相同选项,并且:
    • 您可以将array_walk与提到的一些功能一起使用
    • 您可以获取最后一个元素,并在其上使用 rtrim,如下代码:

对字符串数组使用 rtrim 的代码示例:

<?php
$values = array("['Oct 13',1027],", "['Oct 13',1027],");
$lastIndex = count($values)-1;
$lastValue = $values[$lastIndex];
$values[$lastIndex] = rtrim($lastValue, ',');
<?php
$arr = array(
    "['Jun 13',529],",
    "['Jul 13',550],"
);
$arr[] = rtrim(array_pop($arr), ', 't'n'r');
print_r($arr);
// output:
// Array
// (
//     [0] => ['Jun 13',529],
//     [1] => ['Jul 13',550]
// )

让它成为一个实际的数组,然后内爆。不太确定会是什么(如果 json:你可以做得更好,而不是让值本身成为假数组,但这留给读者作为练习)。

$yourData = array();
while(yourloop){
     //probaby something like: $yourData = array($monthName=>$total_count);
    $yourData[] = "['".$monthName.'&nbsp;'.$shortYear."',".$total_count."]";
}
//now you have an actual array with that data, instead of a fake-array that's a string.
//recreate your array like so:
$data1 = implode(','$yourData);
//or use json_encode.
类似于

@srain但使用array_push的东西。

$values = array("['Oct 13',1027],", "['Oct 13',1027],");
$last = array_pop($values); //pop last element
array_push( $values, rtrim($last, ',') ); //push it by removing comma
var_dump($values);
//output
/*
array
  0 => string '['Oct 13',1027],' (length=16)
  1 => string '['Oct 13',1027]' (length=15)
*/

@ElonThan是对的,@BenFortune也是对的。这是一个 XY 问题,没有其他答案能给你最好的建议——"永远不要手动制作自己的 json 字符串"。

认为你只需要从文本输出中删除最后一个逗号,这样它就会创建一些 javascript 可以解析为索引数组的索引数组的东西。

您应该做的是创建一个多维数组,然后将该数据转换为 json 字符串。 PHP 有一个本机函数可以做到这一点,它保证您将拥有一个有效的 json 字符串(因为它会根据需要转义字符)。

我将演示如何根据while()循环调整脚本。

$result = [];
while ($row = $con->db_fetch_array($graph_data_rs)) {
    $result[] = [
        date('M y', strtotime($row['year'] . '-' . $row['month'])),
        $row['total_count']
    ];
}
echo json_encode($result, JSON_PRETTY_PRINT);

下面是一个在线演示,它将查询的结果集重新创建为输入数组,然后复制循环和结果生成。 https://3v4l.org/cG66l

然后,您所要做的就是在需要时将该字符串回显到渲染的html文档的javascript中。