I feel like there must be an easier way to handle this problem; so I have a multidimensional array like this:
$reports = array(
array("Complete Installation", 1),
array("Register + OSR Install", 0),
array("OSR + Wire", 0),
array("OSR Only", 1),
array("Ground Strap Installation", 2),
array("Meter Only", 2)
);
And I would like to show a percentage out of the total value of the second (well, first, but you know what I mean) column of the Array
. Right now I'm using a foreach
, but it seems really redundant and not very efficient:
foreach($reports as $report) {
$total_val += (int)$report[1];
}
foreach($reports as $report) {
$name = $report[0];
$val = (int)$report[1];
?>
<tr>
<td><?=(stripslashes($name));?></td>
<td><?=($val);?></td>
<td><?=(($val > 0) ? round(($val / $total_val) * 100, 2) : $val);?></td>
</tr>
I feel like there must be a better way to handle that, in-order to get the variable $total_val = 6;
without re-looping the Array
. A way to add up all the $report[1]
's. Any ideas?
If you run PHP 5.5 it's dead easy:
$total = array_sum(array_column($reports, 1));
If you don't, then either the foreach
(there is nothing wrong with it -- on the contrary, simple is good) or some fancy alternatives:
// If you go fancy this should be your choice, the others are slightly inferior
$total = array_reduce($reports, function($sum, $r) { return $sum + $r[1]; }, 0);
or
$total = array_sum(array_map(function($r) { return $r[1]; }, $reports);
or
$total = 0;
array_walk($reports, function($r) use (&$total) { $total += $r[1]; });