The language is PHP. I have one foreach ( $a as $b) and another foreach ($c as $d => $e). How do i combine them to read as one. I tired foreach (($a as $b) && ($c as $d => $e)), but that is rubbish.
A:
This will do what you want I think. It will be advance both arrays equally at the same time throughout your loop. You can always break
manually if $c
is a different size than $a
and you need breaking logic based on array size:
foreach($a as $b)
{
list($d,$e) = each($c);
//continue on with $b, $d and $e all set
}
each()
will advance the array pointer of $c
on each iteration.
zombat
2010-03-31 22:47:01
+1
A:
I don't understand what you're trying to do. If you want to reach them one after the other just use two loops:
foreach ($a as $b) { ... }
foreach ($c as $d => $e) { ... }
If you want all combinations from $a
and $c
:
foreach ($a as $b) {
foreach ($c as $d => $e) {
// do stuff
}
}
I guess you could do something like:
foreach (array_merge($a, $c) as $k => $v) {
...
}
but I wouldn't necessarily advise it.
cletus
2010-03-31 22:47:08
+8
A:
You might be interested in SPL's MultipleIterator
e.g.
// 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
VolkerK
2010-03-31 22:48:11
That's the most interesting peace of code I've seen today. Plus one for that. Do the arrays HAVE to be of equal length, or do you stop iterating on just one of them at some point?
Mark Tomlin
2010-03-31 23:08:40
That depends on whether you set the MultipleIterator::MIT_NEED_ANY or MultipleIterator::MIT_NEED_ALL flag. With MIT_NEED_ALL the iterator stops if any of the inner iterators has no more elements. With MIT_NEED_ANY the iterator continues as long as at least one inner iterator has another element, all other items become NULL. MIT_NEED_ALL is the default.
VolkerK
2010-03-31 23:34:42
Thank you for the info, very cool!
Mark Tomlin
2010-03-31 23:48:26
Thank you for introducing this SPL feature! Plus one too!
hoball
2010-04-01 03:19:09