Skip to content Skip to sidebar Skip to footer

Rendering Array Values In An Html Table

My html page is currently loading with an array of arrays, from previous redirect. Each element in the array should be rendered on a table. So for example the array is [[h1,h2,h3,1

Solution 1:

this is a basic code you can start from:

<?php$array = [['h1','h2','h3','1','2','3','4','5','6'], ['h1','h2','h3','7','8','9','10','11','12']];
echo'<table>';
foreach($arrayas$value) {
    echo'<tr>';
        echo'<td>'.$value[0].'</td>';
        echo'<td>'.$value[1].'</td>';
        echo'<td>'.$value[2].'</td>';
    echo'</tr>';
    echo'<tr>';
        echo'<td>'.$value[3].'</td>';
        echo'<td>'.$value[4].'</td>';
        echo'<td>'.$value[5].'</td>';
    echo'</tr>';
}
echo'</table>';

and this is its output

<table>
    <tbody>
        <tr>
            <td>h1</td>
            <td>h2</td>
            <td>h3</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
        <tr>
            <td>h1</td>
            <td>h2</td>
            <td>h3</td>
        </tr>
        <tr>
            <td>7</td>
            <td>8</td>
            <td>9</td>
        </tr>
    </tbody>
</table>

Solution 2:

You could assign an "id" to the html table to be able to create and attach DOM elements with Javascript

Here you can find some reference about Document object in JS: https://developer.mozilla.org/en-US/docs/Web/API/Document/Document

how to create html elements: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

var createHeaderElem = function(value) {
    var th = document.createElement('th');
    th.appendChild(document.createTextNode(value));
    return th;
}

var createRowElem = function(value) {
    var td = document.createElement('td');
    td.appendChild(document.createTextNode(value));
    return td;
}

var input = ['h1','h2','h3',1,2,3,4,5,6];

var table = document.getElementById('content-table');

var trHeader = document.createElement('tr');

trHeader.appendChild(createHeaderElem(input[0]));
trHeader.appendChild(createHeaderElem(input[1]));
trHeader.appendChild(createHeaderElem(input[2]));

table.appendChild(trHeader);

var trBody = document.createElement('tr');

trBody.appendChild(createRowElem(input[3]));
trBody.appendChild(createRowElem(input[4]));
trBody.appendChild(createRowElem(input[5]));

table.appendChild(trBody);

var trBody = document.createElement('tr');

trBody.appendChild(createRowElem(input[6]));
trBody.appendChild(createRowElem(input[7]));
trBody.appendChild(createRowElem(input[8]));

table.appendChild(trBody);
<tableid="content-table"style="width:50%"></table>

Post a Comment for "Rendering Array Values In An Html Table"