MacMac
MacMac

Reputation: 35341

Altering an array before output as JSON

I need to add a item and a key value to an array once during the while loop before it gets encoded to a JSON object, the output I have is this:

[
    {
        "sid": "1",
        "session_name": "Session Name",
        "session_open": "1"
    },
    {
        "sid": "2",
        "session_name": "Another session",
        "session_open": "1"
    }
]

But i need it to be like this:

[
    {
        "error": "none", <---- this part needs to be added
        "sid": "1",
        "session_name": "Session Name :D",
        "session_open": "1"
    },
    {
        "sid": "2",
        "session_name": "Another session",
        "session_open": "1"
    }
]

This is what I have when going through the while loop:

$sessions = array();
while($row = mysql_fetch_assoc($result))
{
    $sessions[] = $row;
}
mysql_free_result($result);

die(json_encode($sessions));

Upvotes: 1

Views: 286

Answers (1)

deceze
deceze

Reputation: 522461

$sessions[0]['error'] = 'none';
echo json_encode($sessions);
die();

Interesting trick with the die(json_encode()) there, please don't do it again. ;-)

Upvotes: 3

Related Questions