Skip to content

Instantly share code, notes, and snippets.

@trvswgnr
Last active October 16, 2020 18:06
Show Gist options
  • Save trvswgnr/2487166307ca93bb178e46af1377c356 to your computer and use it in GitHub Desktop.
Save trvswgnr/2487166307ca93bb178e46af1377c356 to your computer and use it in GitHub Desktop.
PHP - Filter keys in multidimensional array
<?php
/**
* Filter keys in multidimensional array.
*
* @param mixed $arr The array to filter.
* @param mixed ...$keys Keys to remove. Accepts multiple strings or an array of strings.
* @return array $new Array without specified keys.
*/
function recursive_filter_keys( &$arr, ...$keys ) {
if ( isset( $keys[0] ) && is_array( $keys[0] ) ) {
$keys = $keys[0];
}
$new = $arr;
foreach ( $keys as $key ) {
foreach ( $new as &$value ) {
if ( is_array( $value ) ) {
$value = recursive_filter_keys( $value, $key );
}
}
$new = array_filter(
$new,
function( $k ) use ( $key ) {
return $k !== $key;
},
ARRAY_FILTER_USE_KEY
);
}
return $new;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment