如何在PHP for循环中删除最后一个逗号以构建JSON字符串 [英] How do you remove last comma in a PHP for loop to build a JSON string

查看:156
本文介绍了如何在PHP for循环中删除最后一个逗号以构建JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当从php for SQL查询循环构建JSON字符串时,在构建字符串末尾会有一个不必要的逗号.如何控制最后的逗号.

When building a JSON string from a php for loop from an SQL query there is an unnessary comma at the end of the build string. How do I control the final comma.

$count =  label::grabAll()->count();

echo '{"data": { "graph": {';

for ($x = 0; $x < $count; $x++){

if($x <= 3){
    $cm = ',';
}else{
    $cm .= '';
}

    echo '"'.$x.'": "'.label::grabAll()->results()[$x]->count.'"'.$cm;

}

我从上面的代码中得到了这个结果.

I get this result from the code above.

如何删除最后一个逗号?

How do I remove the final comma?

推荐答案

使用普通的旧对象/数组并使用json_encode.例如

Use plain old objects / arrays and use json_encode. For example

$graph = array_map(function($result) {
    return $result->count;
}, label::graball()->results());

echo json_encode(['data' => ['graph' => $graph]]);

演示〜 https://eval.in/812302

这篇关于如何在PHP for循环中删除最后一个逗号以构建JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆