2017-10-19 9 views
0

PHP를 사용하여 서식이 지정된 HTML 시간표를 표시하려고합니다.PHP 데이터의 다차원 배열을 HTML 테이블로 변환하는 방법은 무엇입니까?

다차원 배열의 데이터를 총 8 개의 열로 구성된 HTML 테이블로 출력하고 싶습니다. 각 세션의 시작 시간을 보여주는 왼쪽에 Mon-Sun 플러스 컬럼이 있습니다.). 행의 양은 하루 동안 몇 개의 세션이 있는지에 따라 다릅니다.

내 솔루션이 어느 정도 작동하며 다음 이미지에서 결과를 볼 수 있지만 어떤 이유로 인해 추가 행이 생성되는 것을 볼 수 있습니다. 하루 동안의 세션 수에 관계없이 항상 추가 행 하나만 있습니다. Current Solution

데이터는 다음과 같이 표시됩니다 : 당신이 볼 수 있듯이

Array 
(
[0] => Array 
    (
     [0] => Array 
      (
       [id] => 1 
       [name] => A Monday Session 
       [start_time] => 10:00 
      ) 

     [1] => Array 
      (
       [id] => 5 
       [name] => Another Monday Session 
       [start_time] => 11:00 
      ) 

     [2] => Array 
      (
       [id] => 6 
       [name] => Yet Another Monday Session 
       [start_time] => 12:00 
      ) 

    ) 

[1] => Array 
    (
     [0] => Array 
      (
      ) 

    ) 

[2] => Array 
    (
     [0] => Array 
      (
       [id] => 8 
       [name] => A Wednesday Session 
       [start_time] => 14:30 
      ) 

    ) 

[3] => Array 
    (
     [0] => Array 
      (
       [id] => 3 
       [name] => A Thursday Session 
       [start_time] => 09:00 
      ) 

    ) 

[4] => Array 
    (
     [0] => Array 
      (
      ) 

    ) 

[5] => Array 
    (
     [0] => Array 
      (
      ) 

    ) 

[6] => Array 
    (
     [0] => Array 
      (
       [id] => 4 
       [name] => A Sunday Session 
       [start_time] => 13:00 
      ) 

    ) 

) 

메인 키는 요일을 나타냅니다. 0 = 월요일, 1 = 화요일 등 매일 다음에 세션 목록이 있습니다. 이 예에서는 월요일에 3 회의 세션이 있고, 수요일과 목요일에는 각각 하나의 세션이 있습니다.

모두 시작 시간이 다릅니다. 시작 시간이 중복 된 세션에 데이터가 도입되면 같은 행을 공유하는 대신 추가 행이 생성됩니다. 목요일 세션을 월요일과 동일하게 변경하려면 10:00로 변경하십시오. Buggy Output

그리고 내 버그 솔루션은 다음과 같습니다. 나는 내가 잘못 가고있는 부분에 주석을 달았다.

// $sessionRows is the array of arrays containing the data above. 

    // Grabs array of session times from $sessionRows that has been sorted and duplicates removed. 
    // Current values: Array ([0] => 09:00 [1] => 10:00 [2] => 11:00 [3] => 12:00 [4] => 13:00 [5] => 14:30) 
    $sessionTimes = $this->getSessionTimes($days); 

    $numOfRows = count($sessionTimes); 
    $numOfCols = $dayIdx; 

    // Create grid with correct dimensions and rows represented by the session times 
    $grid = array(); 
    for($i=0;$i<count($sessionTimes);$i++) { 
     $row = array(); 
     for($j=0;$j<$numOfCols;$j++) { 
      $row[] = '<td></td>'; 
     } 
     $grid[$sessionTimes[$i]] = $row; 
    } 


    // Populate grid with session info added to correct coordinates. 
    for($i=0;$i<$numOfCols;$i++) { 
     echo count($sessionRows[$i]); 
     for($j=0;$j<count($sessionRows);$j++) { 
      $grid[$sessionRows[$i][$j]['start_time']][$i] = $sessionRows[$i][$j]; 
     } 
    } 

    $rows=''; 
    $idx = 0; 
    foreach($grid as $rowArray) { 
     $rows .= '<tr>'; 
     /*** This lines is the problem! It adds the session time as the first column. ***/ 
     $rows .= '<td class="time-col">'.$sessionTimes[$idx].'</td>'; 
     for($i=0;$i<count($rowArray);$i++) { 
      if(!empty($rowArray[$i]['name'])){ 
       $rows .= '<td>'.$rowArray[$i]['name'].'<br>'.$rowArray[$i]['start_time'].'</td>'; 
      } else { 
       $rows .= '<td> - </td>'; 
      } 
     } 
     $rows .= '</tr>'; 
     $idx++; 
    } 

return $rows; 
+0

세션의 요일을 어떻게 알 수 있습니까? – Misunderstood

+0

배열이 정렬되는 방식 때문입니다. 0 = 월요일, 1 = 화요일 등 – Muzzstick

답변

0

문제는 $ sessionTimes 배열에서 array_unique() 함수를 사용하여 중복 된 항목을 제거했기 때문입니다.

이 함수는 제거 된 값의 인덱스를 유지합니다. 따라서 여분의 행은 값없이 생성되었습니다.

이것을 array_values ​​(array_unique ($ array))로 변경하면 재생성 된 키가 허용되어 문제가 해결되었습니다.

한번 봐 주신 분 덕분에, 이전에 이것을 깨달았 으면 좋겠습니다.

0

다음은 적은 수의 루프를 사용하는 대체 솔루션입니다.

시간의 흐름을 반복 한 다음 매일 반복하여 start_time 세션이 일치하는지 여부를 확인하고, 일치하는 경우 출력 테이블에 추가합니다.

<?php 

$sessionTimes = ['09:00', '10:00', '11:00', '12:00', '13:00', '14:30']; 

$schedule = [ 
    [ 
     [ 
      'id' => 1, 
      'name' => 'A Monday Session', 
      'start_time' => '10:00' 

     ], 
     [ 
      'id' => 5, 
      'name' => 'Another Monday Session', 
      'start_time' => '11:00' 

     ], 
     [ 
      'id' => 6, 
      'name' => 'Yet Another Monday Session', 
      'start_time' => '12:00' 

     ], 
    ], 
    [ 
     []  
    ], 
    [ 
     [ 
      'id' => 8, 
      'name' => 'A Wednesday Session', 
      'start_time' => '14:30' 
     ]  
    ], 
    [ 
     [ 
      'id' => 3, 
      'name' => 'A Thursday Session', 
      'start_time' => '09:00' 
     ]  
    ], 
    [ 
     [] 
    ], 
    [ 
     [] 
    ], 
    [ 
     [ 
      'id' => 4, 
      'name' => 'A Sunday Session', 
      'start_time' => '13:00' 
     ] 
    ] 
]; 

$output = '<table><thead><tr><th></th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th></thead><tbody>'; 

foreach ($sessionTimes as $sessionTime) { 
    $output .= '<tr><td>'.$sessionTime.'</td>'; 

    $day = 0; 
    for ($i = 0; $i < count($schedule); $i++) { 
     if ($i == $day) { 
      $sessionAtTime = '<td>-</td>'; 
      foreach ($schedule[$day] as $session) { 
       if (!empty($session) && $session['start_time'] == $sessionTime) { 
        $sessionAtTime = '<td><b>' . $session['name'] . '</b><br>Start: ' . $sessionTime.'</td>'; 
       } 
      } 
      $output .= $sessionAtTime; 
      $day++; 
     } 
    } 

    $output .= '</tr>'; 
} 

$output .= '</tbody></table>'; 

echo $output;