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

PHOTO EMBED

Fri Aug 07 2020 09:11:39 GMT+0000 (Coordinated Universal Time)

Saved 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_copyCOPY

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