将JSON转换为数组并递归更新键(深度n)
function json_overwrite($json_original, $json_overwrite)
{
$original = json_decode($json_original, true);
$overwrite = json_decode($json_overwrite, true);
$original = array_overwrite($original, $overwrite);
return json_encode($original);
}
递归迭代并替换$original
function array_overwrite(&$original, $overwrite)
{
// Not included in function signature so we can return silently if not an array
if (!is_array($overwrite)) {
return;
}
if (!is_array($original)) {
$original = $overwrite;
}
foreach($overwrite as $key => $value) {
if (array_key_exists($key, $original) && is_array($value)) {
array_overwrite($original[$key], $overwrite[$key]);
} else {
$original[$key] = $value;
}
}
return $original;
}
快速测试
$json1 = '{"hello": 1, "hello2": {"come": "here!", "you": 2} }';
$json2 = '{"hello": 2, "hello2": {"come": "here!", "you": 3} }';
var_dump(json_overwrite($json1, $json2));