note 97645 added to function.array-search

From: Date: Fri, 30 Apr 2010 09:06:15 +0000
Subject: note 97645 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-168804@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 : 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 ---- Server IP: 208.69.120.55 Probable Submitter: 193.251.85.97 ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- https://master.php.net/note/edit/97645 Del: integrated -- https://master.php.net/note/delete/97645/integrated Del: useless -- https://master.php.net/note/delete/97645/useless Del: bad code -- https://master.php.net/note/delete/97645/bad+code Del: spam -- https://master.php.net/note/delete/97645/spam Del: non-english -- https://master.php.net/note/delete/97645/non-english Del: in docs -- https://master.php.net/note/delete/97645/in+docs Del: other reasons-- https://master.php.net/note/delete/97645 Reject -- https://master.php.net/note/reject/97645 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#168804) next »