Multiple index variables in PHP foreach loop

前端 未结 8 507
名媛妹妹
名媛妹妹 2020-11-30 04:52

Is it possible to have a foreach loop in PHP with multiple \"index\" variables, akin to the following (which doesn\'t use correct syntax)?

forea         


        
相关标签:
8条回答
  • 2020-11-30 05:07

    to achieve just that result you could do

    foreach (array_combine($courses, $sections) as $course => $section)
    

    but that only works for two arrays

    0 讨论(0)
  • 2020-11-30 05:10

    TRY -

    1)

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

    or 2)

    <?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-11-30 05:13

    If both the arrays are of the same size you can use a for loop as:

    for($i=0, $count = count($courses);$i<$count;$i++) {
     $course  = $courses[$i];
     $section = $sections[$i];
    }
    
    0 讨论(0)
  • 2020-11-30 05:13

    No, this is maybe one of the rare cases PHP's array cursors are useful:

    reset($sections);
    foreach ($courses as $course)
    {
     list($section) = each($sections);
    }
    
    0 讨论(0)
  • 2020-11-30 05:20

    You would need to use nested loops like this:

    foreach($courses as $course)
    {
        foreach($sections as $section)
        {
        }
    }
    

    Of course, this will loop over every section for every course.

    If you want to look at each pair, you are better off using either objects that contain the course/section pairs and looping over those, or making sure the indexes are the same and doing:

    foreach($courses as $key => $course)
    {
        $section = $sections[$key];
    }
    
    0 讨论(0)
  • 2020-11-30 05:20

    What would that do, exactly? Are $courses and $sections just two separate arrays, and you want to perform the same function for the values in each? You could always do:

    foreach(array_merge($courses, $sections) as $thing) { ... }
    

    This makes all the usual assumptions about array_merge, of course.

    Or is it that $sections comes from $course and you want to do something for each section in each course?

    foreach($courses as $course) {
        foreach($sections as $section) {
            // Here ya go
        }
    }
    
    0 讨论(0)
提交回复
热议问题