0 points

php - Search for a key in an array, recursively - Stack Overflow


dashboard

Fri Aug 07 2020 09:11:39 GMT+0000 (UTC)

Posted by @peota #php

function recursiveFind(array $haystack, $needle)
{
    $iterator  = new RecursiveArrayIterator($haystack);
    $recursive = new RecursiveIteratorIterator(
        $iterator,
        RecursiveIteratorIterator::SELF_FIRST
    );
    foreach ($recursive as $key => $value) {
        if ($key === $needle) {
            yield $value;
        }
    }
}

// Usage
foreach (recursiveFind($haystack, $needle) as $value) {
    // Use `$value` here
}
content_copy Copy

https://stackoverflow.com/questions/3975585/search-for-a-key-in-an-array-recursively