dongmangwei3822 2016-10-25 17:07
浏览 103
已采纳

PHP和JSON - 结果中的额外逗号

I'm trying to return json response in the correct format but I am getting an extra 'comma' in the returned code (comma after the last item 'Pencil'):

{
        "results": [{
            "ItemID": 1,
            "ItemName": "Ball"
        }, {
            "ItemID": 2,
            "ItemName": "Pen"
        }, {
            "ItemID": 3,
            "ItemName": "Pencil"
        },
       }]
    }

I tried different things but I can't get rid of it. Would anybody have any idea how to remove it?

The code that i have is this:

 <?php 

 print '{"results":[';
 for ($i=0; $i <$numrows; $i++) {
    $stmt->fetch();

  $JSONArray = array(
        "ItemID" => $ItemID,
        "ItemName" => $ItemName
    );
    print ",";

print json_encode($JSONArray);


 }

 print "]}"

    ?>
  • 写回答

2条回答 默认 最新

  • dou5454954610 2016-10-25 17:09
    关注

    You're doing it ENTIRELY wrong. You're outputting multiple independent JSON strings, which is outright wrong. JSON is a monolithic "structure", and building it piece-wise is highly risky.

    Simple: DOn't do that.

    You build a standard PHP array, then do ONE SINGLE encoding when you're completely done building:

    $arr = array();
    
    for(...) {
        $arr[] = ... add stuff ..
    }
    
    echo json_encode($arr);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU