PHP-如何更新txt文件中的JSON数据? [英] PHP - How to update JSON data in a txt file?
本文介绍了PHP-如何更新txt文件中的JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是保存在文件data.txt
[
{"name":"yekky"},
{"name":"mussie"},
{"name":"jessecasicas"}
...// many rows
]
我想更新文件,使其看起来像这样:
I would like to update the file so it will look like this:
[
{"name":"yekky","num":"1"},
{"name":"mussie","num":"2"},
{"name":"jessecasicas","num":"3"}
...// many rows
]
这是我到目前为止所得到的:
This is what I have got so far:
$json_data = file_get_contents('data.txt');
// What goes here?
如何计算JSON树中有多少行?
And how do I count how many rows there are in the JSON tree?
推荐答案
使用 json_decode()
解码PHP数组中的JSON数据,操作PHP数组,然后使用 json_encode()
重新编码数据.
Use json_decode()
to decode the JSON data in a PHP array, manipulate the PHP array, then re-encode the data with json_encode()
.
例如:
$json_data = json_decode(file_get_contents('data.txt'), true);
for ($i = 0, $len = count($json_data); $i < $len; ++$i) {
$json_data[$i]['num'] = (string) ($i + 1);
}
file_put_contents('data.txt', json_encode($json_data));
这篇关于PHP-如何更新txt文件中的JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文