1

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

['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++;
}
4

5 回答 5

2
  • 如果您在变量中有该数组并想要一个字符串,则可以使用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, ',');
于 2013-10-14T13:04:02.573 回答
1
<?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]
// )
于 2013-10-14T13:01:25.007 回答
0

使它成为一个实际的数组,然后内爆。不确定会发生什么(如果 json:you 可以做得更好,并且不将值本身设为假数组,但这留给读者作为练习)。

$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.
于 2013-10-14T13:06:07.143 回答
0

类似于@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)

*/
于 2013-10-14T13:36:23.077 回答
0

@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 中。

于 2021-07-11T12:36:31.020 回答