简体   繁体   English

PHP 使用 foreach 修改 JSON 文件

[英]PHP Modify JSON file with foreach

i have a json file我有一个 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"}]';

and my forms post data in variable vars="fname"=>"Ameur","lname"=>"KHIL" "fname"=>"Marak","lname"=>"Cristo"我的表单在变量 vars="fname"=>"Ameur","lname"=>"KHIL" "fname"=>"Marak","lname"=>"Cristo" 中发布数据

and i like to insert in between my json content with variable to get the final json like this我喜欢在我的 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"}}]';

For this purpose you can use json_decode() to parse the JSON-String to a PHP-Object.为此,您可以使用 json_decode() 将 JSON-String 解析为 PHP-Object。 Then you just set a new value vars to the given form values.然后,您只需将新值 vars 设置为给定的表单值。

Parsing the JSON-String解析 JSON 字符串

$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"}]');

Adding the new vars value and removing the additional ones.添加新的 vars 值并删除额外的值。 This is just for the first entry but you can do the same for the other entry or even iterate through the array for multiple entries这仅适用于第一个条目,但您可以对另一个条目执行相同的操作,甚至可以遍历数组以获取多个条目

$json[0]->vars = ["fname" => "Marak", "lname" => "Cristo", "Tel1" => $json[0]->Tel1,"Adresse" => $json[0]->Adresse];

unset($json[0]->Tel1);
unset($json[0]->Adresse);

And getting your result in a JSON-String并在 JSON-String 中获取结果

$result = json_encode($json);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM