删除while循环中的最后一个逗号 - PHP [英] Removing Last Comma within while loop - PHP

查看:74
本文介绍了删除while循环中的最后一个逗号 - PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在构建一个小工具来管理数据集,我正在尝试创建一个 JSON 输出以便为我的前端数据提供服务.

现在我在循环中每一行的末尾都有一个额外的逗号.我需要删除它,如果我能找到一种方法在 while 循环内执行此操作,那将是理想的.

这是我的代码:

$sth = mysql_query("SELECT * FROM mapdata");$num_rows = mysql_num_rows($sth);$计数器= 0;回声'[';while($r = mysql_fetch_assoc($sth)) {if (++$counter == $num_rows) {回声 json_encode($r) .'';}别的 {回声 json_encode($r) .',';}}回声]";mysql_close($connection);

这就是我现在得到的回报

<预><代码>[{"col1":"123","col2":"456","col3":"789",},{"col1":"123","col2":"456","col3":"789",}]

这正是我需要的.

<预><代码>[{"col1":"data1","col2":"data2","col3":"data3"},{"col1":"data1","col2":"data2","col3":"data3"}]

任何建议将不胜感激.

解决方案

我喜欢尽可能遵循最佳实践,但在这种特殊情况下,由于我的一些环境限制,我需要偏离最佳实践.我想我会分享我最终使用的解决方案,尽管它过于复杂.

$sth = mysql_query("SELECT name,address,address2,city,state,postal,phone,lat,lng FROM mapdata");$num_rows = mysql_num_rows($sth);$计数器= 0;回声'[';while($r = mysql_fetch_assoc($sth)) {if (++$counter == $num_rows) {echo preg_replace("/^,/",'',str_replace(',}','}',json_encode($r)));}别的 {echo preg_replace("/^,/",'',str_replace(',}','}',json_encode($r)) .',');}}回声]";mysql_close($connection);

I've been building a little tool to manage a dataset, I'm trying create a JSON output in order to serve my front-end the data.

Right now I have an extra comma at the end of every row in the loop. I need to remove it, it would be ideal if I can find a way to do this inside of the while loop.

Here is my code:

$sth = mysql_query("SELECT * FROM mapdata");
$num_rows = mysql_num_rows($sth);
$counter = 0;
echo '[';
while($r = mysql_fetch_assoc($sth)) {
    if (++$counter == $num_rows) {
        echo json_encode($r) . '';
    }
    else {
        echo json_encode($r) . ',';
    }
}
echo "]";
mysql_close($connection);

This is what I'm getting returned now

[
{"col1":"123","col2":"456","col3":"789",},
{"col1":"123","col2":"456","col3":"789",}
]

This is what I need.

[
{"col1":"data1","col2":"data2","col3":"data3"},
{"col1":"data1","col2":"data2","col3":"data3"}
]

Any suggestions would be greatly appreciated.

解决方案

I like to follow best practice whereever possible, but in this particular instance I needed to deviate from best practice due to some environment restrictions I had. I thought I'd share the solution I ended up using, regardless of it being overly complicated.

$sth = mysql_query("SELECT name,address,address2,city,state,postal,phone,lat,lng FROM mapdata");
$num_rows = mysql_num_rows($sth);
$counter = 0;
echo '[';
while($r = mysql_fetch_assoc($sth)) {
    if (++$counter == $num_rows) {
        echo preg_replace("/^,/",'',str_replace(',}','}',json_encode($r)));

    }
    else {
        echo preg_replace("/^,/",'',str_replace(',}','}',json_encode($r)) . ',');
    }
}
echo "]";
mysql_close($connection);

这篇关于删除while循环中的最后一个逗号 - PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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