note 108783 modified in function.array-search by danbrown
| From: | danbrown@php.net | Date: | Thu, 24 May 2012 17:20:26 +0000 |
| Subject: | note 108783 modified in function.array-search by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-188193@lists.php.net to get a copy of this message | ||
I have just tried to add the function of recursive Array Search in order to return all finding keys
in an array instead of the first matching result index, and further expanded search to contain
needle instead of exactly matching:
<?php function
recursiveArraySearchAll($haystack, $needle, $index = null) {
	$aIt = new RecursiveArrayIterator($haystack);
	$it = new RecursiveIteratorIterator($aIt);
	$resultkeys; 						 	while($it->valid())
{ 	if (((isset($index) AND ($it->key() == $index)) OR
(!isset($index))) AND (strpos($it->current(), $needle)!==false)) { //$it->current()
== $needle 	$resultkeys[]=$aIt->key(); //return $aIt->key();
	}
							 	$it->next();
	} 	return $resultkeys; // return all finding in
an array 						 }
; ?> To use the function on your array
search: <?php print_r(recursiveArraySearchAll($your-array,'your-needle-to
match','your-array-index-to-search')
); ?> Simple! and Enjoy!
--was--
I have just tried to add the function of recursive Array Search in order to return all finding keys
in an array instead of the first matching result index, and further expanded search to contain
needle instead of exactly matching:
function recursiveArraySearchAll($haystack, $needle, $index = null)
{
$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);
$resultkeys;
while($it->valid()) {
if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND
(strpos($it->current(), $needle)!==false)) { //$it->current() == $needle
$resultkeys[]=$aIt->key(); //return $aIt->key();
}
$it->next();
}
return $resultkeys; // return all finding in an array
} ;
To use the function on your array search:
print_r(recursiveArraySearchAll($your-array,'your-needle-to
match','your-array-index-to-search') );
Simple! and Enjoy!
http://php.net/manual/en/function.array-search.php