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
精彩评论