Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

WagnerDK's avatar

How do you make a table where parts of the data determine the column?

Sorry if it's a bit strangely described, but I didn't quite know how to describe it.

I am retrieving some data from my database table. One field is called id, the second is called numbers and the third is called letters.

I would like to make a table on my page where the IDs are placed in a cell determined by the numbers (rows) and letters (columns)

So if I have the data: id - number - letter 1 - 1 - A

2 - 1 - B

3 - 2 - B

4 - 3 - B

5 - 3 - A

6 - 2 - A

7 - 3 - C

8 - 2 - C

9 - 1 - C

Then the table will look like this

[-][A][B][C]

[1][1][2][9]

[2][6][3][8]

[3][5][4][7]

I hope it makes sense. Is it possible and how is it done?

I currently have all my data collected in a $tabledata.

0 likes
2 replies
coni's avatar
coni
Best Answer
Level 28

Hi, you can use something like this to prepare variables:

$tableData = collect([
        ['id' => 1, 'number' => 1, 'letter' => 'A'],
        ['id' => 2, 'number' => 1, 'letter' => 'B'],
        ['id' => 3, 'number' => 2, 'letter' => 'B'],
        ['id' => 4, 'number' => 3, 'letter' => 'B'],
        ['id' => 5, 'number' => 3, 'letter' => 'A'],
        ['id' => 6, 'number' => 2, 'letter' => 'A'],
        ['id' => 7, 'number' => 3, 'letter' => 'C'],
        ['id' => 8, 'number' => 2, 'letter' => 'C'],
        ['id' => 9, 'number' => 1, 'letter' => 'C'],
    ]);

    $rows = $tableData->pluck('number')->unique()->sort();
    $columns = $tableData->pluck('letter')->unique()->sort();

and then in your view:

<table>
        <tr>
            <th></th>
            @foreach ($columns as $column)
                <th>{{ $column }}</th>
            @endforeach
        </tr>

        @foreach ($rows as $row)
            <tr>
                <th>{{ $row }}</th>
                @foreach ($columns as $column)
                    <td>{{ $tableData->where('number', $row)->where('letter', $column)->value('id') }}</td>
                @endforeach
            </tr>
        @endforeach
    </table>
1 like
WagnerDK's avatar

@Coni, thank you so much. That was an easy way, i was afraid that it would take alot more.

1 like

Please or to participate in this conversation.