tags:

views:

148

answers:

3

The first array is called $related_docs and the second on is $all_docs. I'm trying to match the "1" value in the first array with the "1" value in the second array.

    Array
(
    [0] => 1
)
Array
(
    [0] => Array
        (
            [id] => 1
            [type_name] => bla1
        )

    [1] => Array
        (
            [id] => 2
            [type_name] => bla2
        )

    [2] => Array
        (
            [id] => 3
            [type_name] => bla3
        )
    )

I'm trying to see if any values from the first array occur in the second array, which it does, but the script prints out nothing but "no". Why is that? I've tried changing $all_docs in the if() statement to $a but that makes no difference.

foreach($all_docs as $a)
  {
   if( in_array($related_docs, $all_docs) )   
   {
    print "yes";
   }
   else print "no";
  }

Do I need to search recursively in the second array?

+2  A: 

You are trying to do a recursive search, which in_array() can't do. It can only very primitively match against the first level of the array you search in.

Maybe this implementation of a recursive in_array() works for what you need.

Alternatively, use something along the lines of:

function id_exists ($search_array, $id)
 {
   foreach ($search_array as $doc)
    if ($doc["id"] == $id) return true;

   else return false;

 }

foreach($all_docs as $a)
  {
   if(  id_exists($related_docs, $a) )   
   {
    print "yes";
   }
   else print "no";
  }
Pekka
Thanks for the suggestion but that recursive search function doesn't work either.
stef
@stef I think the best thing is for you to write a custom function that loops through `$all_docs` and returns true if `$all_docs[i]["id"] == $search_id`.
Pekka
@stef see my updated answer.
Pekka
@stef this is the most logical answer
orlandu63
OK, this works after I changed $doc['id'] = $id to $doc['id'] = $id['id']. Thank you Pekka.
stef
A: 

Try

$a = array(1);
$b = array(
    array('id' => 1, 'type_name' => 'bla1'),
    array('id' => 2, 'type_name' => 'bla2'),
    array('id' => 3, 'type_name' => 'bla3'),
);

Checking if ID in $b exists in $a, so it's the other way round than you described it, but it shouldn't matter for the outcome:

foreach($b as $c) {
    echo in_array($c['id'], $a) ? 'yes' : 'no';
}

It's not generic, but it does what you want.

Gordon
And the downvote is for *what*?
Gordon
No idea so I upvoted you. Seems like a clean solution to me.
Steve Claridge
+2  A: 
function in_array_multiple(array $needles, array $haystacks) {
foreach($haystacks as $haystack) {
    foreach($needles as $needle) {
        if(in_array($needle, $haystack)) {
            return true;
        }
    }
}
return false;
}

(This is an iterative function, not a recursive one.)

orlandu63