简体   繁体   中英

Create json from array in PHP

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.

You are json encoding it twice

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

Just do it once:

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

EDIT Now I understand what you want...

$retval = array();
//as this while you can add as many items to the array as you want
while( $row = $stmt->fetch(PDO::FETCH_OBJ) ){
    $retval[] = $row;
}
echo json_encode( $retval );

Regards, hotzu

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM