«

»

Dec 20 2007

PHP Arrays: Recursive Search – Retaining Array Structure

NOTE: This post assumes that you have working knowledge with PHP and arrays

I was working on a project at work which required a search function. Since we were using Web Services to get the data, I had to create an array looping over each section of the data and appending it to that array. Normally when using straight queries, you can add the search into the query itself. However, with arrays you need to use the array_search function that PHP provides. It would look something like this:

[code lang=”php”]
$look_for = mixed value
$look_in = String

$results = array_search($look_for,$look_in);
[/code]

This works really well if you have a simple array, but once you get into multi-dimensional arrays, array_search just doesn’t cut it. After looking over some user created functions on the PHP website, I was able to find a function that worked very well. It not only recursively searches through the array, but it also keeps the current structure of the array which in other functions got lost. Once you output the array, it “should” be easy to foreach over the results and process your data.

[code lang=”php”]
function array_search_recursive($needle, $haystack,&$tree=Array(),$index=””){
if (is_array($haystack)){
if (count($tree)==0) $tree=array_merge(Array(),$haystack);
foreach($haystack as $k=>$current){
if (is_array($current)){
array_search_recursive($needle,$current,$tree,$index.”[$k]”);
eval(“\$a=\$tree{$index}[{$k}];”); // unset all elements = empty array
if (count($a)==0) //is empty?
eval(“unset(\$tree{$index}[$k]);”); // unset array
}else{
if ($current!=$needle){
eval(“unset(\$tree{$index}[{$k}]);”);
}
}
}
}
return $tree;
}

Usage:
$results = array_search_recursive($look_for, $look_in);
[/code]

I hope this helps!

About the author

Timothy Haroutunian

Timothy Haroutunian is a ServiceNow Cloud Implementation Specialist at Acorio. ServiceNow is an IT Management solution that allows for a complete view of your IT and physical environment.

Permanent link to this article: http://www.armenianeagle.com/2007/12/20/php-arrays-recursive-search-retaining-array-structure/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.