开发者

How to make an Array Find function recursive

开发者 https://www.devze.com 2023-03-25 20:36 出处:网络
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?

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 ($h开发者_开发百科aystack 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.. 


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;
}


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;
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消