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

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

DDD
DDDOriginal
2024-12-24 14:25:10529browse

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

Finding Values in Multidimensional Arrays Using Keys in PHP

Searching for specific key-value pairs in multidimensional arrays can be a tedious task, especially if you don't know the depth of the array. This article presents an efficient PHP function that recursively traverses the array, returning all subarrays that match the search criteria.

The function, search(), takes three parameters: the array to be searched, the key to search for, and the value to match. It uses recursion to explore all levels of the array, checking for the key-value pair at each level.

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;
}

For example, given the array:

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

Calling search($arr, 'name', 'cat 1') would return:

array(0 => array('id' => 1, 'name' => 'cat 1'),
      1 => array('id' => 3, 'name' => 'cat 1'));

For efficiency, an optimized version of the function, search_r(), can be used:

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);
    }
}

This version avoids repetitive array merging, making it more efficient.

The above is the detailed content of How to Efficiently Find Key-Value Pairs in Multidimensional PHP Arrays?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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