如何从PHP文件添加和删除数据到json文件? [英] How to add and delete data to a json file from a php file?
问题描述
如何从php文件插入并删除一个键值对,如JSON文件,如演示如下所示?
insert.php
$ pname =Superman;
$ pid =3;
delete.php
$ pname =皮卡丘;
$ pid =1;
obdatabase.json
var pdatabase ='{pobject:['+
'{pname:皮卡丘,pid:1},'+
'{ pname:Squirtle,pid:2},'+
'{pname:Justinbieber,pid:3}]}';
我会用任何键值构建一个php数组我需要的数据,然后在使用 json_encode($ myArray)
在该数组上输出json格式的字符串之前,根据需要修改该数组(add / remove)。
$ b 注意:如果你已经有一个json字符串可用,你可以使用该字符串来创建一个php数组,使用类似于
$ myArray = json_decode ($ myJsonString)
。 一旦你有一个php数组 $ myArray
你可以像这样添加键值对:
$ myArray ['key'] = $ value;
您可以像下面这样删除键值对:
unset($ myArray ['key']);
How to insert and delete one key value pair from php file to JSON file as shown in demo below?
insert.php
$pname="Superman";
$pid="3";
delete.php
$pname="Pikachu";
$pid="1";
obdatabase.json
var pdatabase= '{ "pobject" : [' +
'{ "pname":"Pikachu" , "pid":"1" },' +
'{ "pname":"Squirtle" , "pid":"2" },' +
'{ "pname":"Justinbieber" , "pid":"3" }]}';
I would build a php array with whatever key-value data I need and then modify that array as needed (add / remove) before using json_encode($myArray)
on that array to output a json formatted string.
Note: if you already have a json string available you can use that string to create a php array using something like $myArray = json_decode($myJsonString)
.
Once you have a php array $myArray
you can add key-value pairs like so:
$myArray['key'] = $value;
And you can remove key-value pairs like so:
unset($myArray['key']);
这篇关于如何从PHP文件添加和删除数据到json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!