Home > Backend Development > PHP Tutorial > How to Recursively Search for a Key in a Multidimensional Array in PHP?

How to Recursively Search for a Key in a Multidimensional Array in PHP?

Mary-Kate Olsen
Release: 2024-11-02 15:58:30
Original
909 people have browsed it

How to Recursively Search for a Key in a Multidimensional Array in PHP?

Recursively Search for a Key in a Multidimensional Array

Problem:

The provided find() method attempts to recursively search for a specific key in an associative array and return the associated value. However, the recursion implementation has an issue.

Solution:

The issue with the original code is related to the recursion. It attempts to return the output of the recursive call directly without handling the case where no match is found at the current level. This can lead to the incorrect return value of "did not find" regardless of whether a match exists deeper in the array.

To rectify this, the following code can be used to handle recursion correctly:

<code class="php">private function find($needle, $haystack) {
    foreach ($haystack as $name => $file) {
        if ($needle == $name) {
            return $file;
        } else if(is_array($file)) { //is folder
            $result = $this->find($needle, $file); //file is the new haystack
            if ($result !== "did not find") {
                return $result;
            }
        }               
    }
    
    return "did not find";
}</code>
Copy after login

This updated function checks if the result of the recursive call is not "did not find," indicating that a match was found at a deeper level. In that case, it returns the found value. Otherwise, it returns the "did not find" value as before.

Alternative Solutions:

In modern PHP versions (5.6 and above), alternative solutions utilizing iterators and/or generators can be more efficient and elegant:

<code class="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) {
            return $value;
        }
    }
}</code>
Copy after login

This function uses iterators to efficiently traverse the multidimensional array and find the first matching key.

Additionally, generators can be employed to iterate over all matching elements, not just the first one:

<code class="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
}</code>
Copy after login

The above is the detailed content of How to Recursively Search for a Key in a Multidimensional Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template