0

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

1
  • 1
    If it's just an array of "arrays that are actually just objects", then foreach(){}. Commented Apr 20, 2022 at 23:17

1 Answer 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];
    }
  }
Sign up to request clarification or add additional context in comments.

1 Comment

This did the job, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.