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.
asked Mar 18, 2014 at 13:10
erdomester
11.9k33 gold badges136 silver badges239 bronze badges
2 Answers 2
You are json encoding it twice
$output[] = json_encode($row2);
print(json_encode($output));
Just do it once:
$output[] = $row2;
print(json_encode($output));
answered Mar 18, 2014 at 13:13
Steve
20.5k5 gold badges47 silver badges71 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
erdomester
This adds another bracket to the result. So it begins with [[["0000000021" instead of [["0000000021"
Steve
I dont understand what you are trying to do here at all - what was the purpose of creating the output array in the 1st place?
erdomester
Actually I messed up the question. I have an array with 6 fields. These fields are populated from 3 SELECT FROM queries. Is there a way to transform this array into an output that normally result from an sql query? The output I need is like [{"APPNAME":"Enhanced Email","LINK":"http... I did this by creating a populating a temporary table then querying it but I think it's not the best way to do.
Steve
@erdomester Please edit your question with your exact expected output so i can help you
erdomester
I accepted this solution since you answered it. However the real answer is
print(json_encode($row2;));. |
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
answered Mar 18, 2014 at 13:16
Zsolt Tolvaly
3,6264 gold badges29 silver badges27 bronze badges
2 Comments
erdomester
This changes the result. It now begins with {"data":[["0000000021", instead of [["0000000021",
Zsolt Tolvaly
where do you want to use it? In a Javascript or a Java application?
lang-php