php foreach repeating twice
-
12-12-2019 - |
Question
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. :)
Solution
foreach(... $r) {
$found = false;
foreach(... $r2) {
if (... == ...) {
$found = true; break;
}
}
if ($found) {
// something
} else {
// something else
}
}
OTHER TIPS
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.