Created
September 28, 2013 22:53
-
-
Save wpscholar/6747565 to your computer and use it in GitHub Desktop.
Recursively traverses a multidimensional array in search of a specific key and returns an array containing the keys that correspond to the path of the first found instance, or an empty array on failure.
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 | |
/** | |
* Recursively traverses a multidimensional array in search of a specific key and returns an | |
* array containing the keys that correspond to the path of the first found instance, or an | |
* empty array on failure. | |
*/ | |
function recursive_multidimensional_array_search_by_key( $key, array $data, $stack = array() ) { | |
if( array_key_exists( $key, $data ) ) { | |
array_push( $stack, $key ); | |
return $stack; | |
} | |
foreach ( $data as $k => $v ) { | |
if( is_array( $v ) ) { | |
array_push( $stack, $k ); | |
$found = call_user_func( __FUNCTION__, $key, $v, $stack ); | |
if( $found ) { | |
return $found; | |
} | |
array_pop( $stack ); | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot! Saved my day. After my approach failed and some investigation, I could ask the proper question and found your solution.