使用PHP计算多个总值的百分比
我有一个多值数组使用PHP计算多个总值的百分比,php,arrays,rounding,percentage,totals,Php,Arrays,Rounding,Percentage,Totals,我有一个多值数组 foreach($results as $row) { $count = $row['count']; $type = $row['type']; $array[$type][] = $count; } 当我将数组输出到表中时,它如下所示 Type Count AA 4 AE 59 AF 13 BB 44 BC 16 BD 36 我现在想要第三列的百分比,但我不知道如何实现 e
foreach($results as $row) {
$count = $row['count'];
$type = $row['type'];
$array[$type][] = $count;
}
当我将数组输出到表中时,它如下所示
Type Count
AA 4
AE 59
AF 13
BB 44
BC 16
BD 36
我现在想要第三列的百分比,但我不知道如何实现
e、 g.AA为5%,AE为39%等
我该怎么做?我没有得到与您建议的相同的计算结果,但以下是我的方法:
$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'));
foreach($results as $row) {
$array[$row['type']]=[$row['count'],(int)round($row['count']/$total*100)];
// or round($row['count']/$total*100).'%' <-- if you want the % sign
}
var_export($array);
您需要知道所有值的总和,然后只需
($count/$sum)*100
array (
'AA' =>
array (
0 => 4,
1 => 2,
),
'AE' =>
array (
0 => 59,
1 => 34,
),
'AF' =>
array (
0 => 13,
1 => 8,
),
'BB' =>
array (
0 => 44,
1 => 26,
),
'BC' =>
array (
0 => 16,
1 => 9,
),
'BD' =>
array (
0 => 36,
1 => 21,
),
)