DEV Community

loading...

Discussion on: Dynamic generated nested table

Collapse
eruizdechavez profile image
Erick Ruiz de Chavez

I do not think this will solve your problem, but might at least give you a different perspective on how to build those tables.

<style>
    table {
        border: 1px solid black;
        width: 100%;
    }

    td {
        border: 1px dotted lightgray;
    }
</style>
<?php

$items = array(
    'lorem', 'ipsum', 'dolor', 'sit', 'amet',
    'consectetur', 'adipiscing', 'elit', 'curabitur', 'tristique',
    'enim', 'in', 'condimentum', 'posuere', 'odio',
    'sem', 'viverra', 'a', 'feugiat', 'purus',
    'quam', 'vitae', 'urna', 'morbi', 'lacinia',
    'volutpat', 'mi', 'id', 'nulla', 'consequat',
    'ut', 'vestibulum', 'scelerisque', 'dui', 'molestie',
    'tempor', 'nibh', 'erat', 'laoreet', 'ex',
    'venenatis', 'nisl', 'massa', 'ac', 'pellentesque',
    'elementum', 'ligula', 'rhoncus', 'eleifend', 'metus',
    'mauris', 'nunc', 'eu', 'risus', 'sodales', 'quisque',
    'varius', 'at', 'duis', 'sapien', 'commodo', 'sed',
    'nisi', 'justo', 'porta', 'luctus', 'vulputate', 'velit', 'cras' );

$maxCellsPerRow = 7;
$maxRowsPerTable = 3;

$index = 0;
$length = count($items);

for (; $index < $length; $index++) {
    if ($index % ($maxCellsPerRow * $maxRowsPerTable) === 0) {
        openTable();
    }

    if ($index % $maxCellsPerRow === 0) {
        openRow();
    }

    printCell($items[$index]);

    if ($index % $maxCellsPerRow === $maxCellsPerRow - 1 || $index === $length - 1) {
        closeRow();
    }

    if ($index % ($maxCellsPerRow * $maxRowsPerTable) === $maxCellsPerRow * $maxRowsPerTable - 1 || $index === $length - 1) {
        closeTable();
    }
}

function openTable()
{
    echo '<table><tbody>';
}

function openRow()
{
    echo '<tr>';
}

function printCell($item)
{
    echo '<td>', $item, '</td>';
}

function closeRow()
{
    echo '</tr>';
}

function closeTable()
{
    echo '</tbody></table>';
}
Enter fullscreen mode Exit fullscreen mode
Collapse
nickknoops_37 profile image
Nick Knoops Author

Ah.. Thanks dude! Will look into your solution. I was trying something along the lines of adding extra counters on the parts where i open/close rows and tables. But this will do aswell