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

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

Susan Sarandon
Release: 2024-12-15 20:39:18
Original
305 people have browsed it

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

Finding Subarrays Based on Key-Value Pairs in Multidimensional PHP Arrays

When traversing multidimensional arrays, it can be challenging to locate specific subarrays based on a key-value pair. However, there's an efficient way to do this recursively, regardless of the array's depth.

Function Implementation:

Let's create a function to search for subarrays meeting the specified conditions:

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

    if (is_array($array)) {
        // Check if the current subarray matches
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }

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

    return $results;
}
Copy after login

Usage Example:

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

We can search for subarrays with the key 'name' and value 'cat 1':

$found = search($arr, 'name', 'cat 1');
print_r($found);
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 when dealing with large arrays, the function can be optimized by avoiding array merging. Instead, it can store results from recursive calls in a temporary array:

function search_optimized($array, $key, $value)
{
    $results = [];
    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

By passing the results array by reference, the function can build the final result efficiently.

The above is the detailed content of How to Efficiently Find Subarrays Based on 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