0

I have been trying different solutions for this problem without success. Problem is this:

I have some results form Zend_Search_Lucene which give say 3 results with the ID of: 2, 3, 4

Then I have some records from an unrelated Query made with Doctrine which gives me say two records with the id ID: 2 and 3.

The results from Search Lucene should show on the page as total of 3 records. Of these I need to check if an ID is equal to another ID of the Docrine query, that is if there is a match ie: 2=2 , 3=3 show something, if not ie: 2=3 show another thing.

Trying to do this with FOREACH twice and an IF ELSE sttement but I get double results on the page:

foreach($this->results as $r):    //  records form search Lucene ie 2, 3, 4

    foreach($this->records2 as $r2){     // records from another table (query) 2 and 3

          if(($r2['id']) == ($r->id)) { 
                                      // do something

                            } else {
                              // dosothing else

    }

...etc.

I understand why the records are repeated twice but I dont' know what is the right way to get the right result. Can someone please help? My apology if there is some silly thing I am doing. :)

Manuel
  • 10,153
  • 5
  • 41
  • 60
firefiter
  • 96
  • 8
  • I'm missing some } at the end of your code, do you have those in your real code and why is the first foreach loop with a : and not with { and at the end a }? – Manuel May 22 '12 at 09:14
  • Can you explain me what would be the right result ? – iiro May 22 '12 at 09:15
  • Sorry I just tried to show the problem the code works fine wiht all teh }. – firefiter May 22 '12 at 09:17
  • The right result is: 2=2. 3=3, 4<> either 2 or 3. So the first two show something and the thir one something else. But there must be only 3 results on the page – firefiter May 22 '12 at 09:17

2 Answers2

3
foreach(... $r) {
  $found = false;
  foreach(... $r2) {
    if (... == ...) {
      $found = true; break;
    }
  }
  if ($found) {
    // something
  } else {
    // something else
  }
}
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

You could eliminate the inner foreach if the array in $this->records2 is a map like this:

array(2 => array('id' => 2));

Then inside the first foreach:

if (isset($this->records2[$r->id])) {
    // do something
} else {
    // do something else
}

In this way, // do something else and // do something are executed at most one time per loop.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309