有一个json文件:
$json='[{"Email":"myemail1@domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2@domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]';
和我的表单在变量中发布数据和"var ="fname"=; Ameur","lname" =祝辞;"KHIL"fname"=祝辞;"Marak","lname" =祝辞;"Cristo"
我喜欢在json内容中插入变量得到最终的json,像这样:$result='[{"Email":"myemail1@domain.com","Name":"company 1","vars":{"fname":"Ameur","lname":"KHIL","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}},{"Email":"myemail2@domain.com","Name":"Company 2","vars":{"fname":"Marak","lname":"Cristo","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}}]';
为此,您可以使用json_decode()将JSON-String解析为PHP-Object。然后,您只需将新值vars设置为给定的表单值。
解析JSON-String$json = json_decode('[{"Email":"myemail1@domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2@domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]');
添加新的变量值并删除额外的变量值。这只是针对第一个条目,其他条目也可以这样做,甚至可以对多个条目进行迭代
$json[0]->vars = ["fname" => "Marak", "lname" => "Cristo", "Tel1" => $json[0]->Tel1,"Adresse" => $json[0]->Adresse];
unset($json[0]->Tel1);
unset($json[0]->Adresse);
并在JSON-String
中获得结果$result = json_encode($json);