eng_coo Posted September 17, 2006 Share Posted September 17, 2006 Hi,I search single dimensional arrays using in_array() function. However i have got a multidimensional array containing users. At the moment i am looping through each array to see if the person exists but as more users get added the code would be very large. Is there an easier way to search a multidimensional array.Here is my code the array has just 2 users in it at moment -[code]$people = array (array ("idx"=>"1", UserName=>"John", Password=>"me", FirstName =>"John"), array ("idx"=>"2", UserName =>"Pete", Password=>"pete", FirstName =>"Pete"));print_r($people);$user ="John";if (in_array($user,$people[0])) {echo "john exists in array 1";} else {if (in_array($user,$people[1])) {echo "john exists in array 2";} else {echo "program not worked!!"; }}echo "<br><br>";[/code]As you can see it searchs each of the internal arrays (0,1). So I i had 60 users it would need 60 loops. There must be a more effective way of searching through an entire mulitdimensional array in one loop as in_array($user, $people) doesnt work as $people shows up as 0=>Array 1=>ArrayAny help much appreciatedcheers John Link to comment https://forums.phpfreaks.com/topic/21057-searching-a-mulitdimensional-array/ Share on other sites More sharing options...
shocker-z Posted September 17, 2006 Share Posted September 17, 2006 Well i've never played with multidimentional arrays before but this seems to work from how far i've tested it..[code]<?php$people = array (array ("idx"=>"1", UserName=>"John", Password=>"me", FirstName =>"John"), array ("idx"=>"2", UserName =>"Pete", Password=>"pete", FirstName =>"Pete"));$user ="John";$arrayno=0;foreach ($people as $person) {$arrayno++; if (in_array($user,$person)) { echo "$user exists in array $arrayno"; }}?>[/code]RegardsLiam Link to comment https://forums.phpfreaks.com/topic/21057-searching-a-mulitdimensional-array/#findComment-93613 Share on other sites More sharing options...
Barand Posted September 17, 2006 Share Posted September 17, 2006 try[code]<?phpfunction array_multi_search(&$haystack, $needle, $key) { foreach ($haystack as $k => $data) { if ($needle == $data[$key]) return $k; } return false;}$people = array ( array ("idx"=>"1", UserName=>"John", Password=>"me", FirstName =>"John"), array ("idx"=>"2", UserName =>"Pete", Password=>"pete", FirstName =>"Pete") );$found = array_multi_search($people, 'Pete', 'FirstName');echo $found;?>[/code] Link to comment https://forums.phpfreaks.com/topic/21057-searching-a-mulitdimensional-array/#findComment-93629 Share on other sites More sharing options...
eng_coo Posted September 19, 2006 Author Share Posted September 19, 2006 Cheers both of you, both ways worked a charm cheersjohn Link to comment https://forums.phpfreaks.com/topic/21057-searching-a-mulitdimensional-array/#findComment-94340 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.