【问题标题】:Fetch data from mysql into JSON using PHP使用 PHP 从 mysql 获取数据到 JSON
【发布时间】:2016-09-22 08:07:48
【问题描述】:

我正在使用以下 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"}}}]

【问题讨论】:

    标签: php arrays json mysqli


    【解决方案1】:

    您需要在循环的每次迭代中初始化 $myArray,例如

    while($row = $user_chats->fetch_array()) { $myArray = array();

    【讨论】:

      猜你喜欢
      • 2011-06-16
      • 2014-05-07
      • 2012-01-22
      • 2012-10-21
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      相关资源
      最近更新 更多