1

I have a multidimensional array like this:

$testarray = array(
    array(
        'First name' => 'Johnny',
        'Last name' => 'Milthers',
        'Age' => '24'
    ),
    array(
        'First name' => 'Toby',
        'Last name' => 'Thomson',
        'Age' => '25'), 
    ),
    array(
        'First name' => 'Jack',
        'Last name' => 'Johnson',
        'Age' => '25'),
    );

How do i pass search strings such as 'John', to then have the array $testarray contain only the first and last array?.

I need to pass a search term, that return the whole subarray if any of the keys values contain that string.

also if i pass "Jack Johnson", $testarray should contain only the last array.

  • Is this possible, or am i going about it the wrong way? how do normal search result work for databases work?

I have been looking at a lot of stack overflow pages (and PHP manual + google), but nothing helped me out, if im posting something that already has an answer, please comment me the link.

Thank you soo much!

1
  • The array you give is full of syntax errors Commented Nov 15, 2013 at 17:59

2 Answers 2

3

Here's one way of doing it, bare in mind it will only work if the search arrays are nested directly in the outer search array.

function search_array($text, $array) {
    return array_filter($array, function($a) use($text){

       return stristr(implode(" ", $a), $text);

    });
}

http://sandbox.onlinephpfunctions.com/code/09e1187ccedba0804de5d797c350e218b05951cd

Sign up to request clarification or add additional context in comments.

Comments

1

I haven't tested this but this should work...

function find_in_array($search, $testarray) {
  $pattern = '*'.$search.'*';
  $array = array_filter($testarray, function($entry) use ($pattern) {
    foreach($entry as $key=>$value) {
      if (fnmatch($pattern, $value)) return true;
    }
    return false;
  });
  return $array;
 }

1 Comment

i tried this and it worked well, except there was an issue (for me) that there is a limit to the number of characters you can test against in fnmatch... so if you're trying to search an array item with more than 260 characters it throws an error.

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.