Get array’s key recursively and create underscore separated string

You can use the RecursiveArrayIterator and the RecursiveIteratorIterator (to iterate over the array recursively) from the Standard PHP Library (SPL) to make this job relatively painless.

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$keys = array();
foreach ($iterator as $key => $value) {
    // Build long key name based on parent keys
    for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
        $key = $iterator->getSubIterator($i)->key() . '_' . $key;
    }
    $keys[] = $key;
}
var_export($keys);

The above example outputs something like:

array (
  0 => 'Student_Address_StreetAddress',
  1 => 'Student_Address_StreetName',
  2 => 'Student_Marks1',
  3 => 'Student_Marks2',
)

Leave a Comment