Jump to content

Searching a mulitdimensional array???


eng_coo

Recommended Posts

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=>Array


Any help much appreciated

cheers

John
Link to comment
https://forums.phpfreaks.com/topic/21057-searching-a-mulitdimensional-array/
Share on other sites

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]


Regards
Liam
try
[code]
<?php
function 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]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.