Skip to content
Advertisement

PHP Replacing element in json

I have this code:

With this code i load a local json file and attempt to array_replace, replacing if it exists or adding if it doesn’t

<?php
// check if all form data are submitted, else output error message
$count = count(explode('&', $_SERVER['QUERY_STRING']));
if ( $count > 0 ) {
    $string = file_get_contents("testconfig.json");
    $json_a = json_decode($string, true);

    $replaced_array = array_replace( $json_a, $_GET );
    $jsondata = json_encode($replaced_array, JSON_PRETTY_PRINT);

    if(file_put_contents('testconfig.json', $jsondata)) echo 'OK';
    else echo 'Unable to save data in "testconfig.json"';
}
else 
{ echo 'Form fields not submitted'; }
?>

let’s say the existing json is something like this:

{
    "key1": "val1",
    "key2": "val2"
}

status.php?myserver[state]=10 and would result in this:

{
    "key1": "val1",
    "key2": "val2",
    "myserver": {
        "state": 10
    }
}

But then i would like to ADD to the myserver element like this: status.php?myserver[mem]=3 and would ADD to the array if it exists, like this:

{
    "key1": "val1",
    "key2": "val2",
    "myserver": {
        "state": 10,
        "mem": 3
    }
}

But my code replaces the whole myserver array..

thanks!

Advertisement

Answer

Use array_merge_recursive().

<?php

$_GET = [
    'myserver' => [
        'state'=>'10'
    ]
];

$existingJson = '{
    "key1": "val1",
    "key2": "val2"
}'; 

$array = json_decode($existingJson, true);

$newArray = array_merge_recursive($array, $_GET);

print_r($newArray);

Result:

Array
(
    [key1] => val1
    [key2] => val2
    [myserver] => Array
        (
            [state] => 10
        )

)

https://3v4l.org/i1YvC

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement