views:

658

answers:

4

The code below doesn't seem to work or find anything on an array. I'm using "in_array" to search for the needle in the stack. I also tried exploding the contents with comma separated and won't work. Any suggestions? Also I tried "array_search".

$q4 = "SELECT domain_name,slots_config.bid FROM slots_pid,slots_config,slots_sites 
WHERE slots_config.bid=slots_pid.bid && slots_sites.aid=slots_pid.aid";
$result4 = mysql_query($q4);

while($row = mysql_fetch_array($result4))
{
    $resultarray[] = $row;
}


if (in_array("test",$resultarray))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }
A: 

in_array() won't work with that sort of array, because it's multi-dimensional.

Your array looks like this:

$resultarray[0]['domain_name'] = 'first row domain name';
$resultarray[0]['bid'] = 'first row bid';
$resultarray[1]['domain_name'] = 'second row domain name';
...

You can't use in_array() to search in that, so you'll have to do it with another method, something like looping over the array, or building $resultarray differently.

Similarly, array_search() doesn't work on multidimensional arrays, so you could do something like looping over the first dimension and array_search()-ing each second dimension.

Let me know if you want more detail.

Chad Birch
+2  A: 

It looks like what you have here is an 'array of arrays'. That is, in your while() loop, $row is an array which corresponds to the data from your mysql query. So each element of $resultarray actually contains an array, rather than a string.

Try doing this: print_r($resultarray). This will display the entire structure of $resultarray, and you can see how you're creating an array-of-arrays.

To use in_array, you woul need to do something akin to in_array("test", $resultarray[0])

rascher
print_r, var_dump are your friends. Understanding your data is faster than trying all the different php functions one by one.
garrow
A: 
$q4 = "SELECT domain_name,slots_config.bid FROM slots_pid,slots_config,slots_sites 
WHERE slots_config.bid=slots_pid.bid && slots_sites.aid=slots_pid.aid";
$result4 = mysql_query($q4);

while($row = mysql_fetch_array($result4))
{
  if (in_array("test",$row))
  {
     echo "Match found";
  }
  else
  {
     echo "Match not found";
  }
}
Itay Moav
A: 

I believe the problem you are having is that it in_array only searches the first dimension of your two dimensional array. I also don't understand why you're loading the whole result into an array before you search (but perhaps that's useful elsewhere in your program).

Try:

 $found = false;
 while($row = mysql_fetch_array($result4))
 {
    if (in_array($needle, $row){
      print "here it is";
      $found = true;
      break;
 }

 if (!$found) {
      print "not found";
 }
acrosman