开发者

Adding items to a JSON encoded array

I am using this solution found on stackoverflow to encode my MYSQL output to a JSON encoded array.

$sth = mysql_query("SELECT ...");

$rows = array();

    while($r = mysql_fetch_assoc($sth)) {
        $rows[] = $r;
    }

print json_encode($rows);

This works great and produces an output of

[{"id":"81","title":"Something Here","start":"2009-10-27 09:00:00"},{"id":"77"开发者_Go百科,"title":"Report on water","start":"2009-10-30 09:00:00"}]

Now I need to put a value of say

"colour":"Blue"

within the JSON encoded array.

So i need the ouput to look like

[{"id":"81","title":"Community Awareness","start":"2009-10-27 09:00:00", "colour":"Blue"},{"id":"77","title":"Write a 10,000 Page Report on Emma","start":"2009-10-30 09:00:00", "colour":"Blue"}]

Does anyone have any solutions on how I could achieve this?

Thanks,

Tim Mohr


Before you call json_encode($rows), just edit the value in the $rows array:

$rows[0]['colour'] = 'Blue'; // changes the colour of the first row in the array

edit in fact, if you just want to add a colour to all of the rows, you can do a simple foreach:

foreach ($rows as &$row) {
    $row['colour'] = 'Blue';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜