Skip to content

Instantly share code, notes, and snippets.

@szepeviktor
Created June 7, 2017 23:46
Show Gist options
  • Save szepeviktor/da5dc89110eda7a8d855b3676f1bfd7f to your computer and use it in GitHub Desktop.
Save szepeviktor/da5dc89110eda7a8d855b3676f1bfd7f to your computer and use it in GitHub Desktop.
Convert a PHP multi-dimensional array to a leaf-only array with full-depth array keys
<?php
function get_leafs( $array ) {
$leafs = array();
if ( ! is_array( $array ) ) {
return $leafs;
}
$array_iterator = new RecursiveArrayIterator( $array );
$iterator_iterator = new RecursiveIteratorIterator( $array_iterator, RecursiveIteratorIterator::LEAVES_ONLY );
foreach ( $iterator_iterator as $key => $value ) {
$keys = array();
for ( $i = 0; $i < $iterator_iterator->getDepth(); $i++ ) {
$keys[] = $iterator_iterator->getSubIterator( $i )->key();
}
$keys[] = $key;
$leaf_key = implode( ' ', $keys );
$leafs[ $leaf_key ] = $value;
}
return $leafs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment