我有一个包含多个值的数组。
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%等。
我该怎么做?
答案 0 :(得分:1)
我没有得到你建议的相同计算,但这是我的方法:
$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);
输出:
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,
),
)