wolves Posted July 23, 2007 Share Posted July 23, 2007 Hi, I trying to build a function that can locate and return the key of an array.... something like $haystack = array( array('id' => 1, 'name' => 'fernando', 'age' => 20), array('id' => 2, 'name' => 'jean', 'age' => 18), array('id' => 3, 'name' => 'paul', 'age' => 23), array('id' => 4, 'name' => 'bob', 'age' => 20), array('id' => 5, 'name' => 'richard', 'age' => 28), ); echo ArrayLocate(array('age' => 18),$haystack); -> 1... 1 is the key of haystack that contain age = 18.... echo ArrayLocate(array('age' => 20),$haystack); -> Array(0,3)... 0,3 are keys of haystack that contain age = 20... echo ArrayLocate(array('age' => 20, 'name' => 'bob'),$haystack); -> 3... 3 is the key of haystack that contain age = 20 and name = 'bob'.... tks Quote Link to comment https://forums.phpfreaks.com/topic/61354-solved-array-locate/ Share on other sites More sharing options...
sasa Posted July 23, 2007 Share Posted July 23, 2007 try <?php function ArrayLocate($srch,$haystack) { $out = array(); foreach ($srch as $k => $v) { foreach ($haystack as $key => $h) { if ($h[$k] == $v) $out[] = $key; } } return $out; } $haystack = array( array('id' => 1, 'name' => 'fernando', 'age' => 20), array('id' => 2, 'name' => 'jean', 'age' => 18), array('id' => 3, 'name' => 'paul', 'age' => 23), array('id' => 4, 'name' => 'bob', 'age' => 20), array('id' => 5, 'name' => 'richard', 'age' => 28), ); $z = ArrayLocate(array('age' => 20),$haystack); print_r($z); ?> Quote Link to comment https://forums.phpfreaks.com/topic/61354-solved-array-locate/#findComment-305326 Share on other sites More sharing options...
wolves Posted July 23, 2007 Author Share Posted July 23, 2007 some modifications.... <?php function ArrayLocate($srch,$haystack) { $out = array(); $cant = array(); foreach ($srch as $k => $v) { foreach ($haystack as $key => $h) { if (($h[$k] == $v) && !in_array($key,$cant)) $out[$key] = $key; else { $cant[] = $key; if(isset($out[$key])) unset($out[$key]); } } } return $out; } $haystack = array( array('id' => 1, 'name' => 'fernando', 'age' => 20,'adr' => 'blue'), array('id' => 2, 'name' => 'fernando', 'age' => 20,'adr' => 'green'), array('id' => 3, 'name' => 'jean', 'age' => 18), array('id' => 4, 'name' => 'paul', 'age' => 23), array('id' => 5, 'name' => 'bob', 'age' => 20), array('id' => 6, 'name' => 'richard', 'age' => 28), ); $z = ArrayLocate(array('name' => 'fernando','adr' => 'green'),$haystack); print_r($z); ?> Quote Link to comment https://forums.phpfreaks.com/topic/61354-solved-array-locate/#findComment-305330 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.