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.. 
Chamilyan
  • 9,347
  • 10
  • 38
  • 67
  • You could use an implementation of [RecursiveFilterIterator](http://www.php.net/manual/en/class.recursivefilteriterator.php). – Wrikken Aug 03 '11 at 18:30
  • Does this question help? http://stackoverflow.com/questions/2504685/php-find-parent-key-of-array – afuzzyllama Aug 03 '11 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. – Chamilyan Aug 03 '11 at 19:08

3 Answers3

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;
}
David Chan
  • 7,347
  • 1
  • 28
  • 49
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;
}
65Fbef05
  • 4,492
  • 1
  • 22
  • 24
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

Community
  • 1
  • 1
Chamilyan
  • 9,347
  • 10
  • 38
  • 67