Jump to content

Archived

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

eng_coo

Searching a mulitdimensional array???

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

Share this post


Link to post
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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites

×

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.