Skip to content

Instantly share code, notes, and snippets.

@iNewLegend
Last active May 12, 2021 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iNewLegend/d3ec79e7509c5f6e44820cb3adf6ae39 to your computer and use it in GitHub Desktop.
Save iNewLegend/d3ec79e7509c5f6e44820cb3adf6ae39 to your computer and use it in GitHub Desktop.
merge json recursive
<?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