Home > Backend Development > PHP Tutorial > How Can I Efficiently Search for Key-Value Pairs in Multidimensional PHP Arrays?

How Can I Efficiently Search for Key-Value Pairs in Multidimensional PHP Arrays?

Mary-Kate Olsen
Release: 2024-12-19 08:29:11
Original
833 people have browsed it

How Can I Efficiently Search for Key-Value Pairs in Multidimensional PHP Arrays?

Recursive Search for Key-Value Pairs in Multidimensional PHP Arrays

Searching for specific key-value pairs within a multidimensional array can be cumbersome. If the array depth is variable, finding a fast and efficient solution is essential.

Recursive Search Function

The following PHP function employs recursion to traverse the array recursively, comparing values for a given key:

function search($array, $key, $value)
{
    $results = array();

    if (is_array($array)) {
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}
Copy after login

Example Usage

Consider the following sample array:

$arr = array(
    0 => array('id' => 1, 'name' => 'cat 1'),
    1 => array('id' => 2, 'name' => 'cat 2'),
    2 => array('id' => 3, 'name' => 'cat 1')
);
Copy after login

To find all subarrays with key 'name' and value 'cat 1', we use:

print_r(search($arr, 'name', 'cat 1'));
Copy after login

Output:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => cat 1
        )

    [1] => Array
        (
            [id] => 3
            [name] => cat 1
        )

)
Copy after login

Efficiency Considerations

For improved efficiency, especially for large arrays, consider using a recursive function that passes results by reference. By sharing a single temporary $results array, performance can be significantly enhanced:

function search_r($array, $key, $value, &$results)
{
    if (!is_array($array)) {
        return;
    }

    if (isset($array[$key]) && $array[$key] == $value) {
        $results[] = $array;
    }

    foreach ($array as $subarray) {
        search_r($subarray, $key, $value, $results);
    }
}
Copy after login

The above is the detailed content of How Can I Efficiently Search for Key-Value Pairs in Multidimensional PHP Arrays?. 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