The bottom line is that I have two JSON files and in one of them there are fields: "string_action_ok": "OK"
and "string_action_cancel": "Cancel"
, but in the other JSON file there is only one field: "string_action_ok": "OK"
, and the field "string_action_cancel": "Cancellation"
is missing. I need to replace the existing fields with new ones and add the ones that don’t exist.
I tried to implement it through str_replace
and foreach
, but nothing worked.
2
Answers
After a while, I finally solved this issue and share it with you. To achieve the result of replacing the existing keys, you should use the array_merge function, a small example:
$array_replaced_keys = array_merge($array_old, $array_new);
And so, what's going on here..
$array_old
is an existing JSON array that we have converted into a list (Array), in the array $array_new there are new keys that will be applied instead of the existing keys in the array$array_old
. Example:$array_old = json_decode('{"action_cancel":"Cancel", "action_ok": "OK", "action_confirm":"Confirm"}', true);
We also proceed with the new array
$array_new
, example:$array_new = json_decode('{"action_confirm":"Confirm new"}', true);
What we should end up with is:
Since there was only
"action_confirm"
in the new array, it was the only one and replaced the old version.You can use native php function array_walk_recursive()
Live code -> https://wtools.io/php-sandbox/bGQj