php - 将数据添加到json中

标签 php mysql json

我想知道新数据是否可以在编码之前添加到 JSON 中?

我通过以下方式从 MySQL 数据库检索数据:

//fetch the data from the database
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
    $to_encode[] = $row;
}

这给了我这个:

[
    {
        name: "aaa"
    },
    {
        name: "bbb"
    }
]

然后我将其编码为 JSON:

$array1 =  json_encode($to_encode)

我想知道在编码之前是否可以向数组中添加更多数据以使其像这样?

[
    {
        name: "aaa"
        age: '5'
    },
    {
        name: "bbb"
        age: '5'
    }
]

或者我应该解码编码的 JSON,添加新值,然后将其编码回来?

最佳答案

简单地你可以这样做:

//fetch the data from the database
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
    $to_encode[] = $row;
}

for ($i = 0; $i < count($to_encode); $i++) {
$to_encode[$i]['age'] = '14';
}

$array1 =  json_encode($to_encode);
print_r($array1);

关于php - 将数据添加到json中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35144818/

相关文章:

jquery - 将 Java 中的 HTML 存储到 MYSQL 数据库中

mysql - 通过命令提示符使用本地计算机 SQL 更新在线 MySQL?

javascript - Javascript多个API提取(youtube)

javascript - linq.js 意外结果

php - MySQL 和 PHP 根据表中的值删除表

php - 如何使用动态键循环 PHP 对象

mysql - 尝试从主机连接到 mysql docker 容器时出现 "Reading initial communication packet"错误

javascript - 按日期排列 json 输出

PHP 代码不允许通过我的表单发送多个输入值

php - 偏移量 0 对 MySQL 结果索引 64 无效(或者查询数据是无缓冲的)