PHP:从数组的最后一项中删除逗号

时间:2013-10-14 12:55:25

标签: php arrays

假设我有这个数组:

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

提前致谢...

5 个答案:

答案 0 :(得分: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]
// )

答案 1 :(得分:1)

  • 如果您在变量中包含该数组并且想要一个字符串,则可以使用implode来获取由 glue char分隔的字符串。
  • 如果您已有字符串,则可以使用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, ',');

答案 2 :(得分:0)

使它成为一个真正的数组,然后崩溃。不确定将会是什么(如果json:你可以做得更好,而不是将这些值自己伪造成数组,但这只会留给读者一个exersize)。

$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.

答案 3 :(得分: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)

*/

答案 4 :(得分:0)

@ElonThan enter image description herewas right @BenFortune。这是一个 so was,其他答案都没有给您最好的建议 - “切勿手动制作自己的 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);

这是一个在线演示,它将您的查询结果集重新创建为输入数组,然后复制循环和结果生成。 XY Problem

然后您所要做的就是在需要的地方将该字符串回显到您呈现的 html 文档的 javascript 中。

相关问题