Is there any fast way to get all subarrays where a key value pair was found in a multidimensional array? I can't say how deep the array will be.
Simple example array:
$arr = array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>2,name=>"cat 2"),
2 => array(id=>3,name=>"cat 1")
);
When I search for key=name and value="cat 1" the function should return:
array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>3,name=>"cat 1")
);
I guess the function has to be recursive to get down to the deepest level.
Code:
Output:
If efficiency is important you could write it so all the recursive calls store their results in the same temporary
$results
array rather than merging arrays together, like so:The key there is that
search_r
takes its fourth parameter by reference rather than by value; the ampersand&
is crucial.FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the call to
search_r
rather than in its declaration. That is, the last line becomessearch_r($subarray, $key, $value, &$results)
.