简体   繁体   中英

How to print 2d php array with header

How can I generate header for printed 2d array in php?

So my array look like this:

$tab=array(
    array(0,1,2,3),
    array(1,2,3,4),
    array(2,3,4,5)
)

This code:

foreach ($tab as $key => $row){
    echo '<b>o<sub>'.($key+1).'</sub></b> ';
    foreach ($row as $item) {
        echo $item.' ';
    }
    echo '<br>';
}

Print this:

0 1 2 3 0 1 2 3
1 2 3 4 1 2 3 4
2 3 4 5 2 3 4 5

But I need this:


0 1 2 3 0 1 2 3
1 2 3 4 1 2 3 4
2 3 4 5 2 3 4 5

Where lenght of rows may be diferent and last column always must be

Thanks for help

You can check if this is the first iteration in the first foreach and if so, add the first line.

foreach ($tab as $key => $row) {

    // If first iteration, add the header
    if ($key === 0)
    {
        foreach ($row as $i => $item)
        {
            // Last header must be 'd'
            if ($i === count($row) - 1)
                echo '<b>d</b>';
            else
                echo '<b>a<sub>' . ($i + 1) . '</sub></b> ';
        }

        echo '<br />';
    }

    // Add the current row
    echo '<b>o<sub>' . ($key + 1) . '</sub></b> ';
    foreach ($row as $item) {
        echo $item . ' ';
    }
    echo '<br />';

}

If the first row is a static row, then you can simply print it using echo function at first.

But if its a dynamic tab as well, then you can use the following code:

$count = count($tab[0]);
for($i = 1; $i <= $count; $i++)
{
    if($i != $count) echo '<b>a<sub>' . ($i + 1) . '</sub></b> ';
    else echo '<b>d</b> ';
}

foreach ($tab as $key => $row){
    echo '<b>o<sub>'.($key+1).'</sub></b> ';
    foreach ($row as $item) {
        echo $item.' ';
    }
    echo '<br>';
}

You can try this, except use <table> or <div> to align your elements.

foreach ($tab[0] as $key => $item)
    echo $key === 0 ? title('&nbsp;&nbsp;', '&nbsp;') : title('a', $key);

echo title('d', '') . '<br>';

function title(string $letter, string $index)
{
    return "<b>{$letter}<sub>{$index}</sub></b>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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