我想知道新数据是否可以在编码之前添加到 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/