Skip to content

Instantly share code, notes, and snippets.

@matt-h
Created June 8, 2017 15:37
Show Gist options
  • Save matt-h/3b3bd648dc780d91536d982db6dd9839 to your computer and use it in GitHub Desktop.
Save matt-h/3b3bd648dc780d91536d982db6dd9839 to your computer and use it in GitHub Desktop.
array_moonwalk test
<?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 );
array(4) {
["one"]=>
int(1)
["two"]=>
int(2)
["three"]=>
int(1)
["four"]=>
int(1)
}
@matt-h
Copy link
Author

matt-h commented Jun 8, 2017

"four" should have a depth of 2 not 1

@matt-h
Copy link
Author

matt-h commented Jun 8, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment