Home >Backend Development >PHP Tutorial >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; }
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"));
We can search for subarrays with the key 'name' and value 'cat 1':
$found = search($arr, 'name', 'cat 1'); print_r($found);
Output:
Array ( [0] => Array ( [id] => 1 [name] => cat 1 ) [1] => Array ( [id] => 3 [name] => cat 1 ) )
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); } }
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!