Skip to content

Instantly share code, notes, and snippets.

@vensires
Created January 10, 2018 14:31
Show Gist options
  • Save vensires/7ea83575660d514a0f58ce0e40c59abb to your computer and use it in GitHub Desktop.
Save vensires/7ea83575660d514a0f58ce0e40c59abb to your computer and use it in GitHub Desktop.
The following function returns the hierarchy of the first-found instance of a key an array. The concept was to take a renderable array, and build the $parents array as required by drupal_array_get_nested_value.
<?php
/**
* Returns the hierarchy of the first found instance of a key in an array.
*/
function drupal_array_get_nested_key_parents($needle, $haystack, &$parents = array()) {
foreach ($haystack as $key => $value) {
if ((string) $key == (string) $needle) {
$parents[] = $key;
return TRUE;
}
elseif (is_array($value)) {
$tempKey = $parents;
$tempKey[] = $key;
if (drupal_array_get_nested_key_parents($needle, $value, $tempKey)) {
$parents = $tempKey;
break;
}
}
}
return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment