Reputation: 11042
I just asked a question about associative arrays and using foreach to retrieve the data but I am struggling to think of a way to build the table I want from this data structure.
I have an array $dailytotals
of the form
Array
(
[204] => Array
(
[1] => Array
(
[leads] => 9
)
[2] => Array
(
[leads] => 15
)
)
[200] => Array
(
[1] => Array
(
[leads] => 7
)
[2] => Array
(
[leads] => 16
)
[3] => Array
(
[leads] => 5
)
)
So I could have any number of sub arrays in the main array with any number of sub arrays within that.
So far I've managed the grand task of building my table header:
<table>
<tr>
<th>Clinic</th>
<?php
// get unique columns - not all clinics will have leads for all columns
$columns = array();
foreach ($dailytotals as $key => $arr) {
$columns = array_unique(array_merge($columns, array_keys($arr)));
}
foreach ($columns as $index => $campaignid) {
echo '<th>' . $campaignid . '</th>';
}
?>
</tr>
But I am completely stuck now how to build the table body.
The structure I want to build is:
Clinic | 1 | 2 | 3 |
___________________________
204 | 9 | 15 | 0 |
200 | 7 | 16 | 5 |
Upvotes: 0
Views: 141
Reputation: 5683
Try this
foreach ($dailytotals as $key => $arr) {
echo '<tr>';
foreach ($columns as $campaignid) {
$val = isset($arr[$campaignid]) ? $arr[$campaignid]['leads'] : 0;
echo '<td>' . $val . '</td>';
}
echo '</tr>';
}
Upvotes: 1
Reputation: 1081
This code is not tested, but try with little modifications (if required)
<table>
<tr>
<th>Clinic</th>
<?php
// get unique columns - not all clinics will have leads for all columns
$columns = array();
$max=0;
foreach ($dailytotals as $key => $arr) {
$columns = array_unique(array_merge($columns, array_keys($arr)));
}
foreach ($columns as $index => $campaignid) {
echo '<th>' . $campaignid . '</th>';
$max=$campaignid;
}
?>
</tr>
<?php
$columns = array();
foreach ($dailytotals as $key => $arr) {
for($i=0;$i< $max;$++)
{
echo "<tr>";
if(is_set($arr[i])
{
echo "<td>".$arr[i]."</td>";
}
else
{
echo "<td>0</td>";
}
echo "</tr>";
}
}
?>
Upvotes: 1
Reputation: 358
You need some nested loops. Try this:
<table>
<tr>
<th>Clinic</th>
<?php
// get unique columns - not all clinics will have leads for all columns
$columns = array();
foreach ($dailytotals as $key => $arr) {
$columns = array_unique(array_merge($columns, array_keys($arr)));
}
foreach ($columns as $index => $campaignid) {
echo '<th>' . $campaignid . '</th>';
}
?>
</tr>
<?php
foreach($dailytotals as $clinic => $data)
{
echo '<tr>';
echo '<td>'.$clinic.'</td>';
foreach($columns as $column)
{
echo '<td>';
echo isset($data[$column]) ? $data[$column]['leads'] : 0;
echo '</td>';
}
echo '</tr>';
}
?>
</table>
Upvotes: 1