douxi9245 2014-03-18 13:10
浏览 35
已采纳

在PHP中从数组创建json

I have this little sql code:

try {
        $stmt = $conn->prepare("SELECT APPID FROM COMMENTROOM WHERE BADGEID=? GROUP BY APPID");
        $stmt->execute(array($badgeID));
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $row2[$i][0] = $row['APPID'];
                $i++;
            }
        } catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
            $server_dir = $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
            header('Location: http://' . $server_dir);
            exit();
    }

When I now print out the result with print(json_encode($row2)); I get the following:

[["0000000021"],["0000000037"],["0000000038"],["0000000039"],["0000000128"],["0000000130"]]

Since I already have this data I don't need to query the database. But I still need to forward it in the same format to my Java app. When I use

$output[] = json_encode($row2);
print(json_encode($output));

I get a different output:

["[[\"0000000021\"],[\"0000000037\"],[\"0000000038\"],[\"0000000039\"],[\"0000000128\"],[\"0000000130\"]]"]

I checked a few stackoverflow questions but I didn't find any that addresses the same problem.

  • 写回答

2条回答 默认 最新

  • dongliao6777 2014-03-18 13:13
    关注

    You are json encoding it twice

    $output[] = json_encode($row2);
    print(json_encode($output));
    

    Just do it once:

    $output[] = $row2;
    print(json_encode($output));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效