dtrphb5597 2013-06-26 23:59
浏览 35
已采纳

在多维数组中添加列的所有给定值的更简单方法是什么?

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?

  • 写回答

1条回答 默认 最新

  • dqs66973 2013-06-27 00:03
    关注

    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]; });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)