The following PHP function finds the node in the multi-dimensional array by matching its key:
<?php
function & findByKey($array, $key) {
foreach ($array as $k => $v) {
if(strcasecmp($k, $key) === 0) {
return $array[$k];
} elseif(is_array($v) && ($find = findByKey($array[$k], $key))) {
return $find;
}
}
return null;
}
$array = [
'key1' => [
'key2' => [
'key3' => [
'key5' => 1
],
'key4' => '2'
]
]
];
$result = findByKey($array, 'key3');
I want the function to return a reference to the node so that if I change $result then the original $array also changes (like Javascript objects).
<?php
array_splice($result, 0, 0, '2');
//Changes $array also since the `$result` is a reference to:
$array['key1']['key2']['key3']
How can I do this?