-
-
Save unnamedfeeling/4a42d5f9bd676592552971f41f166368 to your computer and use it in GitHub Desktop.
PHP Parent Array Iterator
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 = array( | |
array( | |
'id' => 1, | |
'children' => array( | |
array( | |
'id' => 12, | |
'children' => array( | |
) | |
), | |
array( | |
'id' => 13, | |
'children' => array( | |
array( | |
'id' => 131, | |
'children' => array( | |
array( | |
'id' => 1311, | |
'children' => array( | |
) | |
) | |
) | |
) | |
) | |
), | |
array( | |
'id' => 14, | |
'children' => array( | |
) | |
) | |
) | |
) | |
); | |
function search_in_array($needle, $haystack) { | |
$path = array(); | |
$it = new RecursiveIteratorIterator( | |
new ParentIterator(new RecursiveArrayIterator($haystack)), | |
RecursiveIteratorIterator::SELF_FIRST | |
); | |
foreach ($it as $key => $value) { | |
if (array_key_exists('id', $value) && strcasecmp($value['id'], $needle) === 0) { | |
$path = $value; | |
break; | |
} | |
} | |
return $path; | |
} | |
var_dump(search_in_array(1311, $data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment