Let's say i have the following array:
$array = [
['time_spent' => 10, 'rate' => 150],
['time_spent' => 20, 'rate' => 100]
];
I want the table to look like the following:
It has 2 rows and 4 columns (Time Spent, Rate, Total, Grand Total):
The first row will be:
10 | 150 | 10 x 150 = 1500 | 3500
and the second row:
20 | 100 | 10 x 200 = 2000
(3500 is the sum of the total of both records)
Assuming you you wanted to output an HTML table, something like this would work.
$array= [
["time_spent"=> 10, "rate"=> 150],
["time_spent"=> 20, "rate"=> 100]
];
$html = [];
$sum = 0;
foreach ($array as $i => $row) {
$product = $row['rate'] * $row['time_spent'];
$line = "<tr><td>{$row['time_spent']}</td><td>{$row['rate]'}</td>";
$line .= "<td>{$row['time_spent']} x {$row['rate']} = {$product}</td>";
if ($i !== 0) {
$line .= '</tr>';
}
$html[] = $line;
$sum += $product;
}
$rowCount = count($html);
$html[0] .= "<td rowspan='{$rowCount}'>{$sum}</td></tr>";
echo '<table>' . implode('', $html) . '</table>';
EDIT: Changed code to reflect the change in input.
Note that there would be better ways to simply calculate total sum. This method generates the desired display along with the sum with a single loop through the data.
You need to calculate the grand total before you start printing the table. Then you can show it on the first row of the table.
$grand_total = 0;
foreach ($array as $item) {
$grand_total += $item['rate'] * $item['time_spent'];
}
echo "<table>";
foreach ($array as $i => $item) {
$total = $row['time_spent'] * $row['rate'];
echo "<tr><td>{$row['time_spent']}</td><td>{$row['rate']}</td>";
if ($i == 0) { // first row, show grand total
echo "<td>$total</td><td>$grand_total</td>";
} else {
echo "<td colspan='2'>$total</td>";
}
echo "</tr>";
}
echo "</table>";