在输出为JSON之前更改数组

时间:2011-02-16 22:20:07

标签: php arrays json

我需要在while循环期间将一个项和一个键值添加到数组一次,然后才能将其编码为JSON对象,我的输出是:

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

但我需要它是这样的:

[
    {
        "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"
    }
]

这是我在进行while循环时所拥有的:

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

die(json_encode($sessions));

1 个答案:

答案 0 :(得分:3)

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

die(json_encode())的有趣技巧,请不要再这样做了。 ; - )