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条)

报告相同问题?

悬赏问题

  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义