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
CodePudding user response:
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];
}
}