duan1983 2018-04-14 07:29
浏览 390
已采纳

PHP - 计算数组中项目的百分比

I have the following array

Array
(
[0] => Array
    (
        [rate] => normal-rate
        [quantity] => 1
    )

[1] => Array
    (
        [rate] => extra-rate
        [quantity] => 2
    )

[2] => Array
    (
        [rate] => extra-rate
        [quantity] => 1
    )

)

I am trying to work out the percentage of extra-rate items there are in the array, can I do this directly or should I first create a new array by counting the quantity and adding everything together?

  • 写回答

1条回答 默认 最新

  • dongyue4964 2018-04-14 07:38
    关注

    In a one liner it is:

    $pers = count(array_filter($array, function($v) { return $v['rate'] == 'extra-rate'; })) / count($array);
    

    In a simple foreach it is:

    $count = 0;
    foreach ($array as $v) {
        if ($v['rate'] == 'extra-rate') {
            $count++;
        }
    }
    $pers = $count / count($array);
    

    Considering quantity:

    $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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?