Created
December 8, 2016 12:06
-
-
Save rimantoro/35d7b132633fc0d51cdcf0899ee90697 to your computer and use it in GitHub Desktop.
PHP recursive search based on key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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