Table in while loop side by side

白昼怎懂夜的黑 提交于 2019-12-10 11:12:28

问题


in a while loop its creating a list of heading and image links, i want to display it as side by side like in following image.Each heading shold comes as new column and image should come under each category.and only 3 rows.

Here is my code:

<table> 
    <tr>
        <th>Heading 1</th>
        <th>Heading 2</th> 
        <th>Heading 3</th>
    </tr> 
    <?php
        //example array $images = array('Image 1', 'Image 2', 'Image 3', 'Image 4', 'Image 5', );
        for ($i=0; $i<count($images); $i++) { ?> 
        <tr> 
            <td>
            <?php echo $images[$i]; ?></td>
            <td><?php echo $i<3?$images[$i]:''; ?></td>
            <td><?php echo $i<1?$images[$i]:''; ?></td>
        </tr> <?php } ?>
</table>

回答1:


I'am no sure if i understand well what you need, but what about this:

$headings = ['heading 1', 'heading 2', 'heading 3'];
$images = [
    'heading 1' => ['image 1', 'image 2', 'image 3', 'image 4', 'image 5'],
    'heading 2' => ['image 1', 'image 2', 'image 3'],
    'heading 3' => ['image 1']
];

$rows = [];

foreach($headings as $heading){
    $rowId = 0;
    $rows[$rowId][] = '<th>'.$heading.'</th>';

    if(isset($images[$heading])){
        foreach($images[$heading] as $image){
            $rowId += 1;
            if($rowId == 3){
                $rowId = 0;
            }
            $rows[$rowId][] = '<td>'.$image.'</td>';
        }
    }

    for($i = $rowId + 1; $i < 3; $i++){
        $rows[$i][] = '<td>&nbsp;</td>';
    }
}

echo '<table>';
foreach($rows as $row){
    echo '<tr>';
    foreach($row as $column){
        echo $column;
    }
    echo '</tr>';
}
echo '</table>';


来源:https://stackoverflow.com/questions/39804655/table-in-while-loop-side-by-side

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!