Created
June 8, 2017 15:37
-
-
Save matt-h/3b3bd648dc780d91536d982db6dd9839 to your computer and use it in GitHub Desktop.
array_moonwalk test
This file contains 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 | |
/** | |
* Moonwalk an array. | |
* | |
* Deduplicates multidimensional array by flattening it while preserving | |
* the deepest depth and flipping it inside out. Array values become the | |
* keys and the new values contain the depths. | |
* | |
* @since Hyperdrive 1.0.0 | |
* @param array $array A multidimensional array of variable depth. | |
* @param array $accumulator A reference identifier for a stored result. | |
* @param integer [$depth = 1] Starting depth for array search. | |
* @param boolean [$recursing = false] True while doing a moonwalk. | |
* @return A flattened, deduplicated array with leaf node values as keys | |
* and deepest depth of any given leaf as the value. | |
*/ | |
function array_moonwalk( $array, &$accumulator, &$depth = 1, $recursing = false ) { | |
array_walk( $array, function ( $element ) use ( &$accumulator, &$depth, $recursing ) { | |
is_array( $element ) | |
? ++$depth && array_moonwalk( $element, $accumulator, $depth, true ) | |
: $accumulator[ $element ] = $depth; | |
}); | |
$recursing && --$depth; | |
} | |
$antiparticles = [ | |
'one', | |
'two', | |
'three', | |
[ | |
'two', | |
'four', | |
], | |
'four', | |
]; | |
$injectors = []; | |
array_moonwalk( $antiparticles, $injectors ); | |
var_dump( $injectors ); |
This file contains 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
array(4) { | |
["one"]=> | |
int(1) | |
["two"]=> | |
int(2) | |
["three"]=> | |
int(1) | |
["four"]=> | |
int(1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"four" should have a depth of 2 not 1