Json树输出
问题描述:
我想将此json输出更改为下面的样式,任何想法?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 !"},...}
在此先感谢
答
您需要将数据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);
答
好吧,那么你想要的是创建一个数组w ith关键的“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);
您所需的输出无效JSON。你必须用'{}'括住整个字符串:你不能拥有一个裸露的顶级属性 – pb2q 2012-07-30 17:31:37
你为什么要这么做?它不是有效的JSON。你总是需要有一个{object}作为你的JSON的主要输出,或者至少需要一个[array]作为最上面的元素...然后再次,甚至不确定,如果array可以是顶层 – 2012-07-30 17:31:47
@ pb2q,请检查我的编辑。 – iSun 2012-07-30 17:33:21