How do you combine two foreach loops into one

前端 未结 4 1214
故里飘歌
故里飘歌 2020-12-30 11:09

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

4条回答
  •  死守一世寂寞
    2020-12-30 11:42

    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
    

提交回复
热议问题