我有以下数组
Array
(
[0] => Array
(
[rate] => normal-rate
[quantity] => 1
)
[1] => Array
(
[rate] => extra-rate
[quantity] => 2
)
[2] => Array
(
[rate] => extra-rate
[quantity] => 1
)
)
我正在尝试计算数组中额外费率项目的百分比,我可以直接执行此操作,还是应该首先通过计算数量并将所有内容添加到一起来创建新数组?
答案 0 :(得分:3)
在一个班轮中它是:
$pers = count(array_filter($array, function($v) { return $v['rate'] == 'extra-rate'; })) / count($array);
简单的说法就是:
$count = 0;
foreach ($array as $v) {
if ($v['rate'] == 'extra-rate') {
$count++;
}
}
$pers = $count / count($array);
考虑数量:
$ex_qty = 0;
$total_qty = 0;
foreach ($array as $v) {
if ($v['rate'] == 'extra-rate') {
$ex_qty += $v['quantity'];
}
$total_qty += $v['quantity'];
}
$pers = $ex_qty / $total_qty;