1

I have an array parsing function that looks for partial word matches in values. How do I make it recursive so it works for multidimensional arrays?

function array_find($needle, array $haystack)
{
    foreach ($haystack as $key => $value) {
        if (false !== stripos($needle, $value)) {
            return $key;
        }
    }
    return false;
}

Array I need to search through

array(
 [0] =>
  array(
   ['text'] =>'some text A'
   ['id'] =>'some int 1'
 )
 [1] =>
  array(
   ['text'] =>'some text B'
   ['id'] =>'some int 2'
 )
 [2] =>
  array(
  ['text'] =>'some text C'
  ['id'] =>'some int 3'
 )
 [3] =>
  array(
  ['text'] =>'some text D'
  ['id'] =>'some int 4'
 ) 
etc.. 
3
  • You could use an implementation of RecursiveFilterIterator. Commented Aug 3, 2011 at 18:30
  • Does this question help? stackoverflow.com/questions/2504685/… Commented Aug 3, 2011 at 19:02
  • @afuzzyllama, no - I have the key. I need to check if a partial word match exists in any of the values and then get the associative key=>value back. This finds whole value matches and then gives you the parent key, which I don't really need. Commented Aug 3, 2011 at 19:08

3 Answers 3

2
function array_find($needle, array $haystack)
{
    foreach ($haystack as $key => $value) {
        if (is_array($value)) {
            return $key . '->' . array_find($needle, $value);
        } else if (false !== stripos($needle, $value)) {
            return $key;
        }
    }
    return false;
}
Sign up to request clarification or add additional context in comments.

2 Comments

you could modify this function to return an array of keys to the target needle, i give you a breadcrumb like string.
Good call on identifying the parent array in the output result.
1

You'll want to overload your function with an array test...

function array_find($needle, array $haystack)
{
    foreach ($haystack as $key => $value) {
        if (is_array($value)) {
            array_find($needle, $value);
        } else {
            if (false !== stripos($needle, $value)) {
                return $key;
            }
        }
    }
    return false;
}

1 Comment

sorry had window open so long 65Fbef05 beat me to it with the same solution
0

These solutions are not really what I'm looking for. It may be the wrong function to begin with so I created another question that expresses the problem in a more generalized way.

Search for partial value match in an Array

Comments

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.