0

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:

o1 0 1 2 3
o2 1 2 3 4
o3 2 3 4 5

But I need this:

    a1 a2 a3 d
o1 0  1  2   3
o2 1  2  3   4
o3 2  3  4   5

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

Thanks for help

1
  • My 2 cents, it'd be easier if you use python pandas Commented Apr 20, 2017 at 14:24

3 Answers 3

3

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

}
Sign up to request clarification or add additional context in comments.

Comments

0

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>';
}

Comments

0

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>";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.