skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    $array_replaced_keys = array_merge($array_old, $array_new);
    print_r(json_encode($array_replaced_keys)); // Result: {"action_cancel":"Cancel", "action_ok": "OK", "action_confirm":"Confirm new"}
    

    Since there was only "action_confirm" in the new array, it was the only one and replaced the old version.


  2. You can use native php function array_walk_recursive()

    <?php
    
    $arrayJson = [
        [
            "string_action_ok" => "OK",
            "string_action_cancel" => "Cancellation"
        ],
        "another" => [
            [
                "string_action_ok" => "OK",
                "string_action_cancel" => "Cancellation"
            ],
        ]
    ];
    
    array_walk_recursive(
        $arrayJson,
        static function (&$value, $key) {
            if ($key === 'string_action_cancel') {
                $value = 'Cancel';
            }
        }
    );
    
    print_r($arrayJson);
    
    
    

    Live code -> https://wtools.io/php-sandbox/bGQj

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search