chriswhiteley
chriswhiteley

Reputation: 13

Multiple Objects in Foreach Loop

I have the following two foreach loops that are working for me:

foreach ( $pa_speciesreactivityabbrs as $pa_speciesreactivityabbr ) {
echo '<span>' .$pa_speciesreactivityabbr->name. '</span>';
}

foreach ( $pa_speciesreactivitys as $pa_speciesreactivity ) {
echo '<span>' .$pa_speciesreactivity->name. '</span>';
}

However I need to combine the $pa_speciesreactivityabbrs and $pa_speciesreactivitys in the same loop to output $pa_speciesreactivityabbr->name and $pa_speciesreactivity->name together.

I have gone through a number SO answers from other posts, but can't seem to apply them to my situation.

Upvotes: 0

Views: 3223

Answers (1)

Joel Hinz
Joel Hinz

Reputation: 25384

Looks like your objects are in normal arrays. Assuming you don't use associative arrays, you could do this easily by looping through one of them and output data from both at the same time. Like this:

foreach ($array1 as $index => $obj1) {
    echo '<span>' . $obj1->name . $array2[$index]->name . '</span>';
}

I shortened the array names to make it more readable, but I'm sure you see how it works.

Upvotes: 2

Related Questions