Change table layout from array
I have the following array:
$table = array(
1 => array('2.1'=>3, '2.2'=>3, '2.3'=>3),
2 => array('2.1'=>1, '2.2'=>1, '2.3'=>1),
3 => array('2.1'=>2, '2.2'=>2, '2.3'=>2),
4 => array('2.1'=>2, '2.2'=>2, '2.3'=>1),
5 => null,
6 => null,
7 => array('2.1'=>2, '2.2'=>2, '2.3'=>2),
8 => array('2.1'=>2, '2.2'=>2, '2.3'=>2),
9 => array('2.1'=>2, '2.2'=>2, '2.3'=>2),
10 => array('2.1'=>1, '2.2'=>1, '2.3'=>1),
11 => array('2.1'=>3, '2.2'=>1, '2.3'=>1),
12 => array('2.1'=>1),
13 => array('2.1'=>5, '2.2'=>3, '2.3'=>2)
);
I'm reproducing this table
Month clicks clicks2 clicks3
8 2 2 2
9 2 2 2
10 1 1 1
11 3 1 1
12 1
13 5 3 2
It's showing the clicks for three checkboxes on each month. I need to show the table like these instead
Month 8 9 10 11 12 13
Click 2 2 1 3 1 5
Clicks2 2 2 1 1 3
Clicks3 2 2 1 1 2
I actually have
$period =13; //last month
echo '<table><thead>';
echo '<tr><th>8</th><th>9</th><th>10</th><th>11</th><th>13</th></tr>';
echo '</thead>';
for ($i=$period-5; $i <= $period ;$i++){
echo '<tr><th>'.$i.'</th>';
foreach($table[$i] as $checkbox => $val )
{
echo '<td>'.$val.'</td>';
}
echo '</tr>';
}
echo '</table>';
I've been struggling all day without look and it's most probably an easy solution. Anyon开发者_Python百科e see it?
This works for me:
<?
$table = array(
1 => array('2.1'=>3, '2.2'=>3, '2.3'=>3),
2 => array('2.1'=>1, '2.2'=>1, '2.3'=>1),
3 => array('2.1'=>2, '2.2'=>2, '2.3'=>2),
4 => array('2.1'=>2, '2.2'=>2, '2.3'=>1),
5 => null,
6 => null,
7 => array('2.1'=>2, '2.2'=>2, '2.3'=>2),
8 => array('2.1'=>2, '2.2'=>2, '2.3'=>2),
9 => array('2.1'=>2, '2.2'=>2, '2.3'=>2),
10 => array('2.1'=>1, '2.2'=>1, '2.3'=>1),
11 => array('2.1'=>3, '2.2'=>1, '2.3'=>1),
12 => array('2.1'=>1),
13 => array('2.1'=>5, '2.2'=>3, '2.3'=>2)
);
$checkboxes = array();
foreach($table as $monthtable) {
foreach($monthtable as $checkbox=>$clicks) {
if(in_array($checkbox, $checkboxes)) {
continue;
}
else {
$checkboxes[] = $checkbox;
}
}
}
// now we have $checkboxes containing 2.1, 2.2, 2.3, our rows.
?>
<table>
<tr>
<th>Month</th>
<? foreach($table as $month=>$monthtable) {
echo '<th>'.$month.'</th>';
} ?>
</tr>
<? foreach($checkboxes as $checkbox) {
echo '<tr>'
. '<th>'.$checkbox.'</th>';
// assuming this is still in the same order as the last loop.
foreach($table as $monthtable) {
echo '<td>';
if(array_key_exists($checkbox, $monthtable)) {
echo $monthtable[$checkbox];
}
else {
echo '0';
}
echo '</td>';
}
echo '</tr>';
} ?>
</table>
精彩评论