2012-05-18 46 views
0

试图为候补列表清除页面组织一个3层的术语,班级学生数组。这里是我用来创建数组的foreach,但有些不对。由此产生的数组不适合循环并制作 术语>课程>学生的html表格。 我的foreach看起来像这样PHP从查询结果中构造多维数组

foreach ($active_terms as $term) { 
    $waitlists[ $term['term_id'] ] = $term; 
     foreach ($active_courses as $course) { 
      if (($course['term_id'] == $term['term_id']) && ($course['students_waitlisted'] > 0)) { 
      $waitlists[ $term['term_id'] ][ $course['course_id'] ] = $course;     
        foreach ($waitlisted_reservations as $reservation) { 
         if (($term['term_id'] == $reservation['term_id']) 
           && ($course['course_id'] == $reservation['course_id'])) { 
          $waitlists[ $term['term_id'] ][ $course['course_id'] ][ $reservation['reservation_id'] ] = $reservation; 
         } 
        } 
      } 
     }    
} 

所得阵列接近,但看起来是这样的:

Array 
(
[1] => Array 
    (
     [term_id] => 1 
     [term_title] => Summer Session 1 
     [term_begin_date] => June 25 2012 
     [3] => Array 
      (
       [term_id] => 1 
       [course_id] => 3 
       [course_title] => Biology 1 
       [course_student_limit] => 8 
       [students_reserved] => 6 
       [students_registered] => 0 
       [students_waitlisted] => 3 
       [175] => Array 
        (
         [term_id] => 1 
         [course_id] => 3 
         [reservation_id] => 175 
         [reservation_grade_level] => 12 
         [student_sis_id] => 289055 
        ) 
       [173] => Array 
        (
         [term_id] => 1 
         [course_id] => 3 
         [reservation_id] => 173 
         [reservation_grade_level] => 08 
         [student_sis_id] => 111988 
        ) 
      ) 
    ) 
[2] => Array 
    (
     [term_id] => 2 
     [application_id] => 2 
     [term_title] => Summer Session 2 
     [term_begin_date] => July 23 2012 
     [18] => Array 
      (.... 

可能有人请指出我怎么能做出正确的亲子巢?或者是这个数组是正确的,我已经搞乱了如何做嵌套的foreach来建立表?

回答

0

您必须再引入一个级别。例如,替代:

$waitlists[ $term['term_id'] ][ $course['course_id'] ] = $course; 

有了这个:

$waitlists[ $term['term_id'] ]['courses'][ $course['course_id'] ] = $course; 

更新

为了保持自己的理智,你也可以在你的foreach使用引用,如:

foreach ($active_terms as $term) { 
$waitlists[ $term['term_id'] ] = $term; 
    foreach ($active_courses as $course) { 
     if (($course['term_id'] == $term['term_id']) && ($course['students_waitlisted'] > 0)) { 
     $waitlists[ $term['term_id'] ][ $course['course_id'] ] = $course; 

也可以写成:

foreach ($active_terms as $term) { 
    $waitlists[ $term['term_id'] ] = $term; 
    $current_courses = &$waitlists[ $term['term_id'] ]['courses']; 

    foreach ($active_courses as $course) { 
     if (($course['term_id'] == $term['term_id']) && ($course['students_waitlisted'] > 0)) { 
     $current_courses[ $course['course_id'] ] = $course; 

缩短变量名称。你大概可以从那里找出其他的:)

+0

谢谢!我曾尝试添加括号,但它似乎没有道理,但增加了一个新级别的名称可以更容易阅读。 – Jazzy

+0

@ user973828很高兴帮助:) –