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

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

DDD
Release: 2024-12-20 21:26:19
Original
980 people have browsed it

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

Searching for Key-Value Pairs in Multidimensional PHP Arrays

Multidimensional arrays in PHP can be challenging to navigate, especially when searching for specific key-value pairs. This comprehensive guide presents an efficient method for quickly retrieving all subarrays containing a specified key-value pair, irrespective of the array's nesting depth.

The proposed solution is a recursive function named search, which takes an array, a key, and a value as parameters. It checks if the key-value pair exists at the current level of the array and, if so, adds the current subarray to the results. Subsequently, it iterates over each subarray, calling itself recursively to expand the search to deeper levels.

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

By employing recursion, the search function explores the entire array structure, ensuring that all matching key-value pairs are identified.

For instance, given 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

And searching for key=name and value="cat 1", the function will return:

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

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

)
Copy after login

To enhance efficiency, an alternate implementation merges the results of recursive calls into a single $results array instead of creating separate arrays:

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

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

Note that the ampersand & in the parameter list indicates pass-by-reference, ensuring that all recursive calls modify the same $results array.

This robust and versatile solution empowers developers to seamlessly search for key-value pairs in multidimensional PHP arrays, regardless of their depth or complexity.

The above is the detailed content of How to 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template