Searching inside an array for a value in MYSQL output
The code below doesn't work or doesn't find anything in the array. I am using "in_array" to find the needle in the stack. I also tried to hack comma separated content 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";
}
source to share
in_array()
will not work with this type of array because it is multidimensional.
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 this, so you'll have to do it with a different method, something like looping through an array or some other way $resultarray
.
Likewise, array_search()
doesn't work on multidimensional arrays, so you can do something like loop over the first dimension and array_search()
-in every second dimension.
Let me know if you want more details.
source to share
It looks like you have an "array of arrays". That is, in the while () loop, $ row is an array that corresponds to the data in your mysql query. So each element of $ resultarray actually contains an array, not a string.
Try this: print_r($resultarray)
. This will display the entire $ resultarray structure and see how you create an array of arrays.
To use in_array you need to do something similar to in_array("test", $resultarray[0])
source to share
$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";
}
}
source to share
I believe the problem you are having is that it in_array only looks for the first dimension of your two dimensional array. I also don't understand why you are loading the entire result into an array before searching (but it might be 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";
}
source to share