繁体   English   中英

将项目添加到JSON编码的数组

[英]Adding items to a JSON encoded array

我正在使用在stackoverflow上找到的此解决方案将MYSQL输出编码为JSON编码的数组。

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

$rows = array();

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

print json_encode($rows);

这很好用,并产生一个输出

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

现在我需要说一句话

"colour":"Blue"

在JSON编码数组中。

所以我需要输出看起来像

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

有谁对我如何实现这一目标有任何解决方案?

谢谢,

蒂姆·摩尔

在调用json_encode($ rows)之前,只需编辑$ rows数组中的值:

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

实际上,进行编辑 ,如果您只想为所有行添加颜色,则可以执行简单的foreach:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM