代码之家  ›  专栏  ›  技术社区  ›  Donald T

PHP foreach循环中的多个索引变量

  •  31
  • Donald T  · 技术社区  · 14 年前

    foreach 使用多个“索引”变量在PHP中循环,类似于以下(不使用正确的语法)?

    foreach ($courses as $course, $sections as $section)
    

    如果没有,有没有一个好的方法来达到同样的效果?

    8 回复  |  直到 14 年前
        1
  •  49
  •   Will    14 年前

    为了达到你能做到的结果

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

        2
  •  15
  •   RiaD    13 年前

    如果两个数组的大小相同,则可以使用 for 循环为:

    for($i=0, $count = count($courses);$i<$count;$i++) {
     $course  = $courses[$i];
     $section = $sections[$i];
    }
    
        3
  •  6
  •   Alan Geleynse buhbang    14 年前

    您需要使用这样的嵌套循环:

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

    当然,这将在每个课程的每个部分循环。

    如果要查看每一对,最好使用包含课程/节对的对象并在这些对象上循环,或者确保索引相同并执行以下操作:

    foreach($courses as $key => $course)
    {
        $section = $sections[$key];
    }
    
        4
  •  6
  •   T.Todua Laurent W.    12 年前

    (一)

    <?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/>";
    }
    ?>
    

    或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/>";
    }
    ?>
    
        5
  •  3
  •   Daimon    14 年前

    不,因为这些数组可能有其他数量的项。

    你必须明确地写下这样的话:

    for ($i = 0; $i < count($courses) && $i < count($sections); ++$i) {
        $course = $courses[$i];
        $section = $sections[$i];
    
        //here the code you wanted before
    }
    
        6
  •  2
  •   AndreKR    14 年前

    reset($sections);
    foreach ($courses as $course)
    {
     list($section) = each($sections);
    }
    
        7
  •  1
  •   VoteyDisciple    14 年前

    那到底能做什么?是 $courses $sections 只需要两个独立的数组,您想对每个数组中的值执行相同的函数吗?你总是可以做到:

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

    这使得所有通常的假设 array_merge ,当然。

    还是那样 来自 $course 你想为每门课的每一部分做点什么?

    foreach($courses as $course) {
        foreach($sections as $section) {
            // Here ya go
        }
    }
    
        8
  •  0
  •   Edmhs    14 年前

    这样地?

    foreach($array as $b=>$c){
    
    }