Last active
May 12, 2021 12:39
-
-
Save iNewLegend/d3ec79e7509c5f6e44820cb3adf6ae39 to your computer and use it in GitHub Desktop.
merge json recursive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function custom_merge_recursive( $original_schema, $schema_to_merge ) { | |
$get_value_by_path = function ( $path, $data ) { | |
$current = $data; | |
foreach ( $path as $key ) { | |
if ( ! isset( $current[ $key ] ) ) { | |
return null; | |
} | |
$current = $current[ $key ]; | |
} | |
return $current; | |
}; | |
$map_custom_recursive = function ( $callback, $needle ) use ( &$map_custom_recursive ) { | |
$result = []; | |
static $path = []; | |
foreach ( $needle as $key => $value ) { | |
$path [] = $key; | |
$result[ $key ] = $callback( $value, $path ); | |
if ( is_array( $value ) ) { | |
$map_custom_recursive( $callback, $value ); | |
} | |
array_pop( $path ); | |
} | |
return $result; | |
}; | |
return $map_custom_recursive( function ( $value, $path ) use ( $original_schema, $get_value_by_path ) { | |
$original_value = $get_value_by_path( $path, $original_schema ); | |
if ( null === $original_value ) { | |
return $value; | |
} | |
if ( is_array( $original_value ) ) { | |
return array_merge_recursive( $original_value, $value ); | |
} | |
return $original_value; | |
}, $schema_to_merge ); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment