Skip to content

Instantly share code, notes, and snippets.

@rimantoro
Created December 8, 2016 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rimantoro/35d7b132633fc0d51cdcf0899ee90697 to your computer and use it in GitHub Desktop.
Save rimantoro/35d7b132633fc0d51cdcf0899ee90697 to your computer and use it in GitHub Desktop.
PHP recursive search based on key
<?php
$data = [
"key1" => [
"key11" => "Ini level 1.1",
"key12" => [
"key121" => "Ini level 1.2.1",
"key123" => "Ini level 1.2.3"
],
],
"key2" => [
"key21" => [
"key211" => "Ini level 2.1.1",
"key212" => "Ini level 2.1.2",
]
]
];
function recursiveFind(array $array, $needle)
{
$iterator = new RecursiveArrayIterator($array);
$recursive = new RecursiveIteratorIterator(
$iterator,
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($recursive as $key => $value) {
if ($key === $needle) {
return $value;
}
}
}
$getValue = recursiveFind($data, "key211");
var_dump($getValue);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment