【问题标题】:Adding items to a JSON encoded array将项目添加到 JSON 编码的数组
【发布时间】:2010-12-17 17:11:11
【问题描述】:

我正在使用 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"}]

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

谢谢,

蒂姆·莫尔

【问题讨论】:

    标签: php sql arrays json


    【解决方案1】:

    在调用 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';
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-11
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      相关资源
      最近更新 更多