0

我想将此 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 !"},...}

提前致谢

4

2 回答 2

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);
于 2012-07-30T17:35:12.677 回答
2

好的,那么您想要的是创建一个带有键“roominfo”的数组,该键映射到一个 roominfos 数组。

$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);
于 2012-07-30T17:35:01.420 回答