note 114200 deleted from function.array-search by levim

From: Date: Mon, 24 Feb 2014 22:46:04 +0000
Subject: note 114200 deleted from function.array-search by levim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-198662@lists.php.net to get a copy of this message
Note Submitter: Paul Yakubets ---- This class method can search in multidimensional array by multiple conditions: <?php $data = array( array('foo' => 'test4', 'bar' => 'baz'), array('foo' => 'test', 'bar' => 'baz'), array('foo' => 'test1', 'bar' => 'baz3'), array('foo' => 'test', 'bar' => 'baz'), array('foo' => 'test', 'bar' => 'baz4'), array('foo' => 'test4', 'bar' => 'baz1'), array('foo' => 'test', 'bar' => 'baz1'), array('foo' => 'test3', 'bar' => 'baz2'), array('foo' => 'test', 'bar' => 'baz'), array('foo' => 'test', 'bar' => 'baz'), array('foo' => 'test4', 'bar' => 'baz1') ); class Stdlib_Array { public static function multiSearch(array $array, array $pairs) { $found = array(); foreach ($array as $aKey => $aVal) { $coincidences = 0; foreach ($pairs as $pKey => $pVal) { if (array_key_exists($pKey, $aVal) && $aVal[$pKey] == $pVal) { $coincidences++; } } if ($coincidences == count($pairs)) { $found[$aKey] = $aVal; } } return $found; } } $result = Stdlib_Array::multiSearch($data, array('foo' => 'test4', 'bar' => 'baz1')); var_dump($result); ?> Will produce: array(2) { [5]=> array(2) { ["foo"]=> string(5) "test4" ["bar"]=> string(4) "baz1" } [10]=> array(2) { ["foo"]=> string(5) "test4" ["bar"]=> string(4) "baz1" } }

« previous php.notes (#198662) next »