0

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?

3 Answers 3

2

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";
  }
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the suggestion but that recursive search function doesn't work either.
@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.
@stef this is the most logical answer
OK, this works after I changed $doc['id'] = $id to $doc['id'] = $id['id']. Thank you Pekka.
2
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.)

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.