Reputation: 138
I would like to create a html table from the following array. But this table is a bit complicated to make, because the header should contain the different sizes (34 - 41) and the location should be only displayed once per line. Also the first [0] => 124 shouldn't be displayed, like this:
sizes
loc 34 - 35 - 38 - 39 - 40 - 41
124 1 1 2 2 1 1
424 1 1 0 0 0 0
1512 1 1 0 0 0 0
1612 0 0 1 1 2 2
1711 0 0 1 1 1 1
In my search for the solution, I've found this code, but this shows everything on two lines.
echo '<table border="1">';
echo '<tr>';
foreach( $result as $key => $value )
{
if( is_array($value) )
{
foreach($value as $key => $column) {
echo ' <th colspan="1">'.$key.'</th>';
}
}
else
{
echo '<th colspan="1">No subcat</th>';
}
}
echo '</tr>';
//Data
echo '<tr>';
foreach( $result as $key => $value )
{
if( is_array($value) )
{
foreach($value as $key => $column) {
echo '<td>'.$column.'</td>';
}
}
else
{
echo '<td>'.$value.'</td>';
}
}
echo '</tr>';
The array
Array
(
[0] => Array
(
[Loc] => 124
[0] => 124
[34] => 1
[35] => 1
[38] => 2
[39] => 2
[40] => 1
[41] => 1
)
[1] => Array
(
[Loc] => 424
[0] => 424
[34] => 1
[35] => 1
[38] => 0
[39] => 0
[40] => 0
[41] => 0
)
[2] => Array
(
[Loc] => 1512
[0] => 1512
[34] => 1
[35] => 1
[38] => 0
[39] => 0
[40] => 0
[41] => 0
)
[3] => Array
(
[Loc] => 1612
[0] => 1612
[34] => 0
[35] => 0
[38] => 1
[39] => 1
[40] => 2
[41] => 2
)
[4] => Array
(
[Loc] => 1711
[0] => 1711
[34] => 0
[35] => 0
[38] => 1
[39] => 1
[40] => 1
[41] => 1
)
)
Upvotes: 1
Views: 38
Reputation: 192
You must display only the first line in the first foreach
. (You showed all the lines).
You must break;
after one foreach
Then, display each data from the second foreach
on a single line via
<tr>
(You were showing all the lines in one tr
)
Also, you do not have to display the values with key "0"
Here is the corrected code
echo '<table border="1">';
echo '<tr>';
foreach( $result as $key => $value )
{
if( is_array($value) )
{
foreach($value as $key => $column) {
if($key!='0')echo ' <th colspan="1">'.$key.'</th>';
}
}
else
{
echo '<th colspan="1">No subcat</th>';
}
break;
}
echo '</tr>';
//Data
foreach( $result as $key => $value )
{
echo '<tr>';
if( is_array($value) )
{
foreach($value as $key => $column) {
if($key!='0')echo '<td>'.$column.'</td>';
}
}
else
{
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
Upvotes: 2