HOBALL 筆記簿

April 1, 2010

PHP: Run two foreach loops at the same time

Filed under: PHP — Tags: , , , — hoball @ 11:25 am

@reference: http://stackoverflow.com/questions/2556998/how-do-you-combine-two-foreach-loops-into-one

SPL MultipleIterator
@reference: http://docs.php.net/class.multipleiterator

// ArrayIterator is just an example, could be any Iterator.
$a1 = new ArrayIterator(array(1, 2, 3, 4, 5, 6));
$a2 = new ArrayIterator(array(11, 12, 13, 14, 15, 16));

$it = new MultipleIterator;
$it->attachIterator($a1);
$it->attachIterator($a2);

foreach($it as $e) {
  echo $e[0], ' | ', $e[1], "\n";
}

Prints

1 | 11
2 | 12
3 | 13
4 | 14
5 | 15
6 | 16

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: