note 79535 modified in function.array-search by danbrown

From: Date: Wed, 29 Apr 2009 12:56:48 +0000
Subject: note 79535 modified in function.array-search by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153971@lists.php.net to get a copy of this message
Make a recursive search on array and return the matches elements in the same structure than the original array and unset empty arrays: <?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; } ?> --was-- Sorry, in the previous note empty arrays not unset. Add three comment code lines: 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; } http://php.net/manual/en/function.array-search.php

« previous php.notes (#153971) next »