0

I want to change this json output to below style, Any ideas?

My Code:

$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);

Current Output :

{"roomInfo":[],"0":{"uid":"50","name":"ali","message":"arz adab !"},"1":{"uid":"50","name":"ali","message":"arz adab !"},...}

Desired Output :

{"roomInfo" : [{"uid":"50","name":"ali","message":"arz adab !"},{"uid":"50","name":"ali","message":"arz adab !"},...}

Thanks in advance

2
  • 1
    your desired output isn't valid JSON. You must enclose the whole string with {}: you can't have a bare top-level attribute Commented Jul 30, 2012 at 17:31
  • Why would you want this? it's not valid JSON. You always need to have an { object } as the main output of your JSON or need at least a [ array ] as the top element... And then again, not even sure, if array can be top level Commented Jul 30, 2012 at 17:31

2 Answers 2

4

You need to push the data to roomInfo key over your rows.

$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);
Sign up to request clarification or add additional context in comments.

Comments

2

Ok, then what you want is to create an array with a key "roominfo" that maps to an array of 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.