我想将此json输出更改为以下样式,任何想法?
我的代码:
$queryFunctions = $db->getChatRoomData($userID , $userName, $userMessage, $roomID);
$rows['roomInfo'] = array();
while ($result = mysql_fetch_array($queryFunctions, MYSQL_ASSOC))
{
$row['uid'] = $result['uid'];
$row['name'] = $result['userName'];
$row['message'] = $result['messageText'];
array_push($rows, $row);
}
echo json_encode($rows);
当前输出:
{"roomInfo":[],"0":{"uid":"50","name":"ali","message":"arz adab !"},"1":{"uid":"50","name":"ali","message":"arz adab !"},...}
期望的输出:
{"roomInfo" : [{"uid":"50","name":"ali","message":"arz adab !"},{"uid":"50","name":"ali","message":"arz adab !"},...}
提前致谢
答案 0 :(得分:4)
您需要将push
数据roomInfo
改为行{。}}。
$queryFunctions = $db->getChatRoomData(
$userID , $userName, $userMessage, $roomID
);
$rows = array('roomInfo' => array());
while ($result = mysql_fetch_array($queryFunctions, MYSQL_ASSOC))
{
$row['uid'] = $result['uid'];
$row['name'] = $result['userName'];
$row['message'] = $result['messageText'];
array_push($rows['roomInfo'], $row);
}
print json_encode($rows);
答案 1 :(得分:2)
好的,那么你想要的是创建一个数组,其中包含一个映射到roominfos数组的密钥“roominfo”。
$queryFunctions = $db->getChatRoomData($userID , $userName, $userMessage, $roomID);
$rows['roomInfo'] = array();
while ($result = mysql_fetch_array($queryFunctions, MYSQL_ASSOC))
{
$row['uid'] = $result['uid'];
$row['name'] = $result['userName'];
$row['message'] = $result['messageText'];
array_push($rows['roomInfo'], $row);
}
echo json_encode($rows);