'Searching within PHP multi dimensional array to return results within parent array
I'm looking for a function to search for a matching keyword in a multi dimensional array and return the corresponding name and path values.
$search_array = array(
array(
'keywords' => array('apple', 'orange'),
'name' => 'Url One',
'path' => 'http://www.urlone.com'
),
array(
'keywords' => array('bananna'),
'name' => 'Url Two',
'path' => 'http://www.urltwo.com'
)
)
If there's a better way to structure this array to make it simpler the that would also be great, thanks
Solution 1:[1]
This can be accomplished using array filter:
$matches = array_filter($search_array, function($array){
return in_array('bananna', $array['keywords']);
});
Or using a foreach loop:
$matches = [];
foreach ($search_array as $key => $array) {
if (in_array('apple', $array['keywords'])) {
$matches[$key] = $search_array[$key];
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
