-1

I have a json file:

$json='[{"Email":"[email protected]","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"[email protected]","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"

and I like to insert in between my json content with variable to get the final json like this:

$result='[{"Email":"[email protected]","Name":"company 1","vars":{"fname":"Ameur","lname":"KHIL","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}},{"Email":"[email protected]","Name":"Company 2","vars":{"fname":"Marak","lname":"Cristo","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}}]';
2
  • Please accept the given answer if it helped you. Commented Oct 29, 2021 at 9:30
  • duplicate of: stackoverflow.com/questions/50444893/… Commented Oct 30, 2021 at 19:36

1 Answer 1

2

For this purpose you can use json_decode() to parse the JSON-String to a PHP-Object. Then you just set a new value vars to the given form values.

Parsing the JSON-String

$json = json_decode('[{"Email":"[email protected]","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"[email protected]","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]');

Adding the new vars value and removing the additional ones. 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

$result = json_encode($json);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.