简体   繁体   English

如何将PHP数据的多维数组转换为HTML表?

[英]How to convert multi-dimensional array of PHP data to an HTML table?

I'm trying to display a formatted HTML timetable using PHP. 我正在尝试使用PHP显示格式化的HTML时间表。

I would like to output data from a multi-dimensional array to an HTML table that's formatted with a total of 8 columns (a column for each day Mon-Sun plus a column on the left showing the start times for each session). 我想将数据从多维数组输出到HTML表格,该表格的格式总共为8列(周一至周日每天一列,左侧为每个会话的开始时间一列)。 The amount of rows depends on how many sessions there are for each day. 行的数量取决于每天有多少会话。

My solution works to a degree and you can see the output in the following image but you can also see that an extra row is generated for some reason. 我的解决方案在一定程度上有效,您可以在下图中看到输出,但是您也可以看到由于某种原因生成了额外的行。 It's always just one extra row no matter the amount of sessions in a day. 无论一天的会话量如何,它总是仅多一行。 当前解决方案

The data is represented like this: 数据表示如下:

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
            )

    )

)

As you can see the main keys represent the days of the week. 如您所见,主键代表星期几。 0 = Monday, 1 = Tuesday etc. Each day then has a list of sessions. 0 =星期一,1 =星期二,等等。然后每一天都有一个会话列表。 In this example Monday has 3 sessions, and Wed,Thu,Sun each also have one. 在此示例中,星期一有3个会话,而周三,周四,周日也都有一个会话。

Notice that they all have different starting times. 请注意,它们都有不同的开始时间。 The moment a session is introduced to the data with a duplicate start time, then extra rows are also created instead of sharing the same row. 在将会话引入具有重复开始时间的数据的那一刻,然后还将创建额外的行,而不是共享同一行。 See output with the Thursday session changed to 10:00 to be the same as Monday: 星期四会话的输出更改为10:00,与星期一相同: 越野车输出

And here is my buggy solution. 这是我的越野车解决方案。 I've marked with a comment the line where I'm going wrong. 我在注释中标记了我要出错的行。

    // $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;

The problem was the $sessionTimes array was having duplicates removed by using the array_unique() function. 问题在于$ sessionTimes数组已使用array_unique()函数删除了重复项。

This function was preserving the index of the removed values. 此功能保留删除值的索引。 So the extra rows were being created without value. 因此,多余的行是没有价值的。

Changing this to array_values(array_unique($array)) allowed regenerated keys and fixed the issue. 将其更改为array_values(array_unique($ array))允许重新生成密钥并解决了该问题。

Thanks to anyone who had a look at it, wish I'd realised this earlier! 感谢所有看过它的人,希望我早点意识到这一点!

Here is an alternative solution that uses less loops. 这是使用较少循环的替代解决方案。

What it does is it loops through the times, then loops through each day to determine whether the session start_time matches, if it does, add it to the output table. 它的作用是循环遍历时间,然后循环遍历每天以确定会话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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM