note 97645 modified in function.array-search by danbrown
| From: | danbrown@php.net | Date: | Fri, 30 Apr 2010 12:09:41 +0000 |
| Subject: | note 97645 modified in function.array-search by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-168813@lists.php.net to get a copy of this message | ||
If you want a very simple way of searching a value through a multidimensionnal array here's a
trick :
<?php
function recursiveArraySearch($haystack, $needle, $index = null)
{
$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);
while($it->valid())
{
if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() ==
$needle)) {
return $aIt->key();
}
$it->next();
}
return false;
}
?>
So let's take a misc multi-dimensionnal array :
<?php
$std = new stdClass();
$std->name = 'luke';
$std->age = '25';
$std->sex = 'M';
$array = array( array('type'=>'dog', 'name'=>'butch',
'sex'=>'m', 'breed'=>'boxer'),
array('type'=>'dog', 'name'=>'fido',
'sex'=>'m', 'breed'=>'doberman'),
'simpleValue',
array('type'=>'cat',
'name'=>'tiddles','sex'=>'m',
'breed'=>'maine coon'),
array('type'=>'horse',
'name'=>'ed','sex'=>'m',
'breed'=>'clydesdale'),
$std);
echo recursiveArraySearch($array, '25', 'age'); // returns 5
echo recursiveArraySearch($array, '25', 'name'); // returns false
echo recursiveArraySearch($array, 'simpleValue'); // returns 2
echo recursiveArraySearch($array, 'fido'); // returns 1
?>
--was--
If you want a very simple way of searching a value through a multidimensionnal array here's a
trick :
function recursiveArraySearch($haystack, $needle, $index = null)
{
$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);
while($it->valid())
{
if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() ==
$needle)) {
return $aIt->key();
}
$it->next();
}
return false;
}
So let's take a misc multi-dimensionnal array :
$std = new stdClass();
$std->name = 'luke';
$std->age = '25';
$std->sex = 'M';
$array = array( array('type'=>'dog', 'name'=>'butch',
'sex'=>'m', 'breed'=>'boxer'),
array('type'=>'dog', 'name'=>'fido',
'sex'=>'m', 'breed'=>'doberman'),
'simpleValue',
array('type'=>'cat',
'name'=>'tiddles','sex'=>'m',
'breed'=>'maine coon'),
array('type'=>'horse',
'name'=>'ed','sex'=>'m',
'breed'=>'clydesdale'),
$std);
echo recursiveArraySearch($array, '25', 'age'); // returns 5
echo recursiveArraySearch($array, '25', 'name'); // returns false
echo recursiveArraySearch($array, 'simpleValue'); // returns 2
echo recursiveArraySearch($array, 'fido'); // returns 1
http://php.net/manual/en/function.array-search.php