Reputation: 1734
I have the following array ($arrayres) (example data)
Array
(
[0] => Array
(
[description] => somedata
[amount] => 52,6
[b_id] => Array
(
[0] => 138950106
[1] => 138950106
)
)
[1] => Array
(
[description] => somedata
[amount] => 4,9
[b_id] => Array
(
[0] => 138911857
[1] => 138911857
)
)
)
Then I have a query that returns the b_id in its results as well. I need to find which of the b_id's are included in the array and their respective position in the array. So I perform an array_rearch
while ($dbres = $res->fetchRow(MDB2_FETCHMODE_ASSOC))
{
$key = array_search($dbres['b_id'], $arrayres);
if ($key)
{
$keys[] = $key;
}
}
But there seems to be no match. print_r($keys) is always empty, although there are results that contain the b_id's in question.
What am I doing wrong?
Upvotes: 0
Views: 2570
Reputation: 7078
The array you are searching does not contain the b_id you are searching for. It contains an array that contains that bid.
So you need to loop yourself through the array of data you have, or supply array_search the whole array, if you can. One way would be this:
function has_bid($arrayres, $bid) {
foreach ($arrayres as $k => $v) {
// This is assuming $bid is an array with 2 integers.
if ($v['bid'] == $bid) {
return $k;
}
// And this is assuming $bid is one of the integers.
/*
Here, array_search will search for the integer in an array that contains
the values you are searching for in the first level,
not inside an array that is inside another one.
You can think of it as array_search searching the first level of it.
*/
if (array_search($bid, $v) !== false) {
return $k;
}
}
return false;
}
And you would use this function like so:
$key = has_bid($arrayres, $dbres['bid']);
if ($key !== false) {
// do something...
}
Upvotes: 1
Reputation: 29912
When you do array_search($dbres['b_id'], $arrayres);
you're searching for keys onto "the first layer" of that nested array and, of course, theare are only 0
or 1
as keys
You could do something like that
for($i=0;$i<count($arrayres);$i++) {
array_search($dbres['b_id'], $arrayres[$i]['b_id']);
if ($key)
{
$keys[] = $key; /* just follow your logic */
}
}
and that has to be inserted into the while loop
Upvotes: 2