Reputation: 427
I have a dynamic multidimensional array with unique keys in all dimensions. (Array keys can be anything, below array is just an example to show that all keys are unique.)
$data = array(
'0' => array(
'0-0' => array(
'0-0-0' => array(
'0-0-0-0' => 'some value',
'0-0-0-1' => 'some value',
),
'0-0-1' => array(
'0-0-1-0' => 'some value',
'0-0-1-1' => 'some value',
'0-0-1-2' => 'some value',
),
'0-0-2' => array(
'0-0-2-0' => 'some value',
'0-0-2-1' => 'some value',
),
'0-0-3' => array(
'0-0-3-0' => 'some value',
),
),
'0-1' => array(
'0-1-0' => array(
'0-1-0-0' => 'some value',
'0-1-0-1' => 'some value',
),
'0-1-1' => array(
'0-1-1-0' => 'some value',
'0-1-1-1' => 'some value',
),
'0-1-2' => array(
'0-1-2-0' => 'some value',
'0-1-2-1' => 'some value',
),
),
),
'1' => 'some value',
'2' => array(
'2-0' => 'some value',
'2-1' => array(
'2-1-0' => 'some value',
),
),
);
Depth and count of sub-arrays are dynamic. All keys are unique, but they don't have a pattern as the above example.
I need to find the exact position (with all parents hierarchically) of a given key in this array. For example;
get_key_position('0-1-2-1', $data);
should return array('0', '0-1', '0-1-2', '0-1-2-1')
get_key_position('2-1-0', $data);
should return array('2', '2-1', '2-1-0')
get_key_position('1', $data);
should return array('1')
Upvotes: 2
Views: 423
Reputation: 4474
I didn't make the effort to go and look at the different links cited by comments under your question, so maybe I'm re-inventing the wheel :)
Anyway, this seems to work in any situation:
function look4key($key, $data, $path = []) {
if (is_array($data)) {
foreach ($data AS $localKey => $value) {
$localKey = (string)$localKey;
$localPath = array_merge($path, [$localKey]);
if ($localKey == $key) {
return $localPath;
}
if ($nestedPath = look4key($key, $value, $localPath)) {
return $nestedPath;
}
}
}
# returns NULL if $key not found
}
Hope it's rather self-explanatory, except this pitfall: (string)$localKey
is needed for keys like '0'
, '1'
, etc, because of this automatic cast (look at php manual):
Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8.
Upvotes: 1