Pravin Bankar Pravin Bankar - 2 months ago 6
PHP Question

Display table dynamically from multidimensional array

all masters.
I have an below array

Array
(
[1] => Array
(
[2] => Array
(
[0] => 11
[1] => 12
[2] => 13
)

[3] => Array
(
[0] => 21
)

)

[2] => Array
(
[2] => Array
(
[0] => 11
[1] => 12
[2] => 13
)

[3] => Array
(
[0] => 21
)

)

[3] => Array
(
[2] => Array
(
[0] => 11
[1] => 12
[2] => 13
)

[3] => Array
(
[0] => 21
)

)

)


In above Array The first Node [1] is my color value. Inside it [2] is my size attribute and this value. in same child node their is [3] is my type attribute and its value. I want to display this in HTML Table format like this.
1 2 3 should be goes into according this below table will be display.



<table>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<tr>
<td>1</td>
<td>11</td>
<td>21</td>
</tr>
<tr>
<td>1</td>
<td>12</td>
<td>21</td>
</tr>
<tr>
<td>1</td>
<td>13</td>
<td>21</td>
</tr>
<tr>
<td>2</td>
<td>11</td>
<td>21</td>
</tr>
<tr>
<td>2</td>
<td>12</td>
<td>21</td>
</tr>
<tr>
<td>2</td>
<td>13</td>
<td>21</td>
</tr>

</table>





if their is no 3 node table will be display like this



<table>
<tr>
<th>1</th>
<th>2</th>
</tr>
<tr>
<td>1</td>
<td>11</td>
</tr>
<tr>
<td>1</td>
<td>12</td>
</tr>
<tr>
<td>1</td>
<td>13</td>
</tr>
<tr>
<td>2</td>
<td>11</td>
</tr>
<tr>
<td>2</td>
<td>12</td>
</tr>
<tr>
<td>2</td>
<td>13</td>
</tr>

</table>







Please Help me to achieve this.

Answer

The solution using range, array_map, end and current functions:

// $arr is your initial array
$parent_keys = range(1, count(current($arr)) + 1);
echo "<table><tr>" . 
        implode("", array_map(function($v){
            return "<th>".$v."</th>"; }, $parent_keys)
        );
echo "</tr>";

foreach ($arr as $k => $item) {
    if (count($item) > 1 && is_array(end($item))) $last = current(end($item));
    reset($item);
    foreach (current($item) as $v) {
        echo "<tr><td>$k</td><td>$v</td>". (isset($last)? "<td>$last</td>" : "") ."</tr>";
    }
}

echo "</table>";

DEMO link

Comments