How do you combine two foreach loops into one

前端 未结 4 1207
故里飘歌
故里飘歌 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
    
    0 讨论(0)
  • 2020-12-30 12:00

    1) First method

    <?php
    $FirstArray = array('a', 'b', 'c', 'd');
    $SecondArray = array('1', '2', '3', '4');
    
    foreach(array_combine($FirstArray, $SecondArray) as $f => $n) {
        echo $f.$n;
        echo "<br/>";
    }
    ?>
    

    or 2) Second method

    <?php
    $FirstArray = array('a', 'b', 'c', 'd');
    $SecondArray = array('1', '2', '3', '4');
    
    for ($index = 0 ; $index < count($FirstArray); $index ++) {
      echo $FirstArray[$index] . $SecondArray[$index];
      echo "<br/>";
    }
    ?>
    
    0 讨论(0)
  • 2020-12-30 12:00

    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.

    0 讨论(0)
  • 2020-12-30 12:01

    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.

    0 讨论(0)
提交回复
热议问题