Skip to content
Advertisement

php dynamic table from muldimentional array

can you give me idea how to implement this idea for “dynamic” html table. I have an array

$arr = array(
  array(
       'label' => 'First name',
       'data' => array(
           array('fname' => 'John'),
           array('fname' => 'Ralph'),
       ),
  ),
  array(
       'label' => 'Last name',
       'data' => array(
           array('lname' => 'Doe'),
           array('lname' => 'Loren'),
       ),
  ),
  array(
       'label' => 'Description',
       'data' => array(
           array('description' => 'Something bout John'),
           array('description' => 'Something about Ralph'),
       ),
  ),
);

Now from the keys ‘label’ im creating the table columns

---------------------------------------
|First Name | Last Name | Description |
---------------------------------------

The problem is how to put ‘fname’ keys in the first column, ‘lname’ in the second and ‘description’ in the third.

With this part of code im trying to put the data in all columns

    private function tableBody()
{
    $data = $this->data;
    $table = '<tbody>';

    foreach($data as $key => $value){
        foreach($value['data'] as $k => $v){
            $table .= '<tr>';
            foreach($v as $col => $name){
                $table .= '<td>' . $name . '</td>';
            }
            $table .= '</tr>';
        }
    }

    $table .= '</tbody>';

    return $table;
}

Also my idea is not to hard code array keys for multiple usage(except label and data).

Advertisement

Answer

First I would remap the data to process it in loops.

$labels = [];
$rows = [];
foreach($arr as $column) {
    $label = $column['label'];
    $labels[] = $label;
    foreach($column['data'] as $key => $value) {
        $rows[$label][] = $value;
    }
}

Now print out the labels with the headline.

echo "<table>n";
echo "<tr>";
foreach($labels as $label) echo "<th>{$label}</th>";
echo "</tr>n";

Iterate through the rows and create the HTML.

$labelCount = count($labels);
$rowCount = count($rows[$labels[0]]);

while($rowCount) {
    echo "<tr>";
    for ($i = 0; $i < $labelCount; $i++) {
        $current = array_shift($rows[$labels[$i]]);
        $value = reset($current);
        echo "<td>{$value}</td>";
    }
    echo "</tr>n";
    $rowCount--;
}
echo "</table>n";

This gives a table like below

<table>
<tr><th>First name</th><th>Last name</th><th>Description</th></tr>
<tr><td>John</td><td>Doe</td><td>Something bout John</td></tr>
<tr><td>Ralph</td><td>Loren</td><td>Something about Ralph</td></tr>
</table>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement