简体   繁体   中英

PHP - Calculate percentage of items in array

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM