Last active
October 16, 2020 18:06
-
-
Save trvswgnr/2487166307ca93bb178e46af1377c356 to your computer and use it in GitHub Desktop.
PHP - Filter keys in multidimensional array
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 | |
/** | |
* 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