我使用以下PHP代码从我的数据库中获取一些数据。它包含这些聊天中用户之间的聊天和消息。我想返回两个用户的信息以及他们交换的消息。我的测试数据有两个ID为1和2的聊天。聊天1中有两条消息,但是出于某种原因,它们都会被退回到聊天1和2中。我不确定是什么问题在我的代码中。
$response = array();
$myArray = array();
while($row = $user_chats->fetch_array())
{
$myArray["chatId"] = $row["chat_id"];
$myArray["user1_id"] = $row["user1"];
$myArray["user2_id"] = $row["user2"];
$myArray["user1_name"] = $user1_name;
$myArray["user2_name"] = $user2_name;
$myArray["user1_profile_pic"] = $result_user1["profile_pic"];
$myArray["user2_profile_pic"] = $result_user2["profile_pic"];
$messages = array();
$chat_idd = $row["chat_id"];
$chat_messages = mysqli_query($conn,"SELECT * FROM messages WHERE chatID = '$chat_idd' ORDER BY timestamp ASC");
$count = 1;
while($roww = $chat_messages->fetch_array()) {
if ($row["chat_id"] == $roww["chatID"]) {
$messages["message_id"] = $roww["message_id"];
$messages["sender"] = $roww["sender"];
$messages["chatId"] = $roww["chatID"];
$messages["text"] = $roww["text"];
$messages["timestamp"] = $roww["timestamp"];
$myArray["message"][$count] = $messages;
$count = $count + 1;
}
else {
$myArray["message"]= 0;
}
}
$response[] = $myArray;
}
echo json_encode($response);
产生以下回应:
[{"chatId":"1","user1_id":"32132132","user2_id":"2121","user1_name":"dwqd",
"user2_name":"dqdwdw","user1_profile_pic":"http:\/\/graph.facebook.com\/dwqwqdqdwdw\/picture?type=large","user2_profile_pic":"WDQdwqwqddqwdqwdq","message":{"1":{"message_id":"24242241","sender":"32132132","chatId":"1","text":"hello i am",
"timestamp":"2016-05-24 17:13:08"},"2":{"message_id":"421421","sender":"32132132",
"chatId":"1","text":"great","timestamp":"2016-05-24 17:15:08"}}},{"chatId":"2","user1_id":"23413524635","user2_id":"32132132","user1_name":false,
"user2_name":"dwqd","user1_profile_pic":
WDQdwqwqddqwdqwdq" ,"user2_profile_pic":"http:\/\/graph.facebook.com\/32132132\/picture?type=large",
"message":{"1":{"message_id":"24242241","sender":"32132132","chatId":"1","text":"hello i am",
"timestamp":"2016-05-24 17:13:08"},"2":{"message_id":"421421","sender":"32132132","chatId":"1",
"text":"great","timestamp":"2016-05-24 17:15:08"}}}]

答案 0 :(得分:1)
你需要在循环的每次迭代中初始化$ myArray,例如
while($row = $user_chats->fetch_array()) {
$myArray = array();