Hy guys and girls :). Here is my problem. I have two tables in database(users and comments). One user can post 1 or more comments. I want to retreive data from database in JSON format. When I retrive data, I get format like this
[{"username":"kurtMarko","message":"Kako si mama"},{"username":"kurtMarko","message":"kako si tata"},{"username":"kurtMarko","message":"kako si brate"},{"username":"kurtMarko","message":"kako si sestro"}]
but I want to retrive data like
[{"username":"kurtMarko","message":[{"Kako si mama"},{"kako si tata"},{"kako si brate"},{"kako si sestro"}]]
Do you have any idea, suggestions. Every comment will help me. Thank you very much. Here is my code
require("config.inc.php");
$query = "SELECT comments.message, users.username
FROM comments
LEFT JOIN users ON users.username = comments.username";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
} catch(PDOException $ex){
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows) {
$response = array();
foreach ($rows as $row) {
$post["username"]= $row["username"];
$post["message"] = $row["message"];
array_push($response, $post);
}
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
{"Kako si mama"},{"kako si tata"}it is not a json and you can not create it byjson_encode. Only by direct manipulation with the string."Kako si mama","kako si tat"as a elements of a string array, and not as objects. OP can you confirm/deny?["Kako si mama","kako si tata", "kako si brate", "kako si sestro"]. A json library should be able to do that for you.["Kako si mama","kako si tata", "kako si brate", "kako si sestro"]be json with key message. If I put$post["message"] = array()insted$post["message"] = $row["message"], then put foreach loop, i get what I want, but then I get as many as I have usernames in database. Is there solution to get only one username with all messages