PHP,计算多个项目的百分比 [英] Php, calculate percentage on multiple items
本文介绍了PHP,计算多个项目的百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我总共有5个项目,我想根据提交的[数据]计算百分比.结果将用于饼图.
I have 5 items in total, and I would like to calculate percentage based on [data] filed. The result will be used for pie chart.
Array
(
[0] => Array
(
[label] => Item1
[data] => 849
)
[1] => Array
(
[label] => Item2
[data] => 657
)
[2] => Array
(
[label] => Item3
[data] => 571
)
[3] => Array
(
[label] => Item4
[data] => 538
)
[4] => Array
(
[label] => Item5
[data] => 446
)
)
使用:
(5/[data])*100
无法产生正确的结果,我不确定如何执行正确的计算.
does not produce correct result, and I'm not sure how to perform proper calculations.
推荐答案
我认为您想要对所有项目进行汇总以首先获得总金额,然后确定每个项目的百分比
I think what you want is to sum up all the items to get the total sum first and then determine the percentage of each item
$sum = array[0]['data'] + array[1]['data'] ...
$pc0 = array[0]['data'] / $sum * 100;
...
我将循环留给OP.
// 至于缺少更好的事情,这里是一个减少功能以获得总和:
// As for a lack of something better to do, here is a reduce function to get the sum:
$sum = array_reduce($data_array, function($v1, $v2){ return $v1 + $v2['data']; });
这篇关于PHP,计算多个项目的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文