php 计算每一行的列值与整列总和之间的百分比

ctehm74n  于 2023-01-08  发布在  PHP
关注(0)|答案(1)|浏览(185)

我希望根据特定列值和该列中所有值的总和计算数组中每一行的百分比。
样本数据:

$results = [
    ['type' => 'AA', 'count' => 4],
    ['type' => 'AE', 'count' => 59],
    ['type' => 'AF', 'count' => 13],
    ['type' => 'BB', 'count' => 44],
    ['type' => 'BC', 'count' => 16],
    ['type' => 'BD', 'count' => 36]
];

预期结果:

[
  ['type' => 'AA', 'count' => 4, 'percent' => '2%'],
  ['type' => 'AE', 'count' => 59, 'percent' => '34%'],
  ['type' => 'AF', 'count' => 13, 'percent' => '8%'],
  ['type' => 'BB', 'count' => 44, 'percent' => '26%'],
  ['type' => 'BC', 'count' => 16, 'percent' => '9%'],
  ['type' => 'BD', 'count' => 36, 'percent' => '21%'],
]

我的代码:

foreach($results as $row) {
   $count = $row['count'];
   $type = $row['type'];
   $array[$type][] = $count;
}
zzzyeukh

zzzyeukh1#

在对每一行执行运算之前,需要对所有行的count值求和(对于示例数据,总数为172)。
然后循环遍历这些行,计算百分比并将新的关联行推入新数组。
代码:(Demo

$results = [
    ['type' => 'AA', 'count' => 4],
    ['type' => 'AE', 'count' => 59],
    ['type' => 'AF', 'count' => 13],
    ['type' => 'BB', 'count' => 44],
    ['type' => 'BC', 'count' => 16],
    ['type' => 'BD', 'count' => 36]
];
$total = array_sum(
    array_column($results, 'count')
); // 172

foreach($results as &$row) {
    $row['percent'] = round($row['count'] / $total * 100, 0) . '%';
}
var_export($results);

或者,您可以使用array_map()中的现代arrow函数将新列合并到每一行中,而不是使用经典循环。

var_export(
    array_map(
        fn($row) => $row + ['percent' => round($row['count'] / $total * 100, 0) . '%'],
        $results
    )
);

输出(来自任一方法):

array (
  0 => 
  array (
    'type' => 'AA',
    'count' => 4,
    'percent' => '2%',
  ),
  1 => 
  array (
    'type' => 'AE',
    'count' => 59,
    'percent' => '34%',
  ),
  2 => 
  array (
    'type' => 'AF',
    'count' => 13,
    'percent' => '8%',
  ),
  3 => 
  array (
    'type' => 'BB',
    'count' => 44,
    'percent' => '26%',
  ),
  4 => 
  array (
    'type' => 'BC',
    'count' => 16,
    'percent' => '9%',
  ),
  5 => 
  array (
    'type' => 'BD',
    'count' => 36,
    'percent' => '21%',
  ),
)

相关问题