Home > Enterprise >  Count number of occurrences of a key in a multidimensional array
Count number of occurrences of a key in a multidimensional array

Time:12-21

I want to calculate the average from a key contained in the array.

Array
(
    [123456] => Array
        (
            [Log] => 2793
            [Approve] => 1724
            [Accept] => 13863
        )

    [123457] => Array
        (
            [Log] => 2606
            [Classify] => 730
            [FirstLineSupport] => 83339
            [Escalate] => 14689501
            [Fulfill] => 14772840
        )

    [123458] => Array
        (
            [Log] => 2700
            [Approve] => 16152972
            [Fulfill] => 73006092
            [Accept] => 729914
            [Review] => 27033
        )
)

In this case I need to calculate the average of key "Fulfill". So I need to calculate:

(14772840   73006092) / 2 = 43889466

I know I can sum the values using:

$sum = array_sum(array_column($arr, 'Fulfill'));

But how can I divide by the number of occurrences of the key?

PHP online: https://onlinephp.io/c/35153

CodePudding user response:

Just one line more:

$args = array_column($arr, 'Fulfill');
$sum = array_sum($args)/count($args);

CodePudding user response:

Put the result of array_column() in a variable. Then you can get the length of that array.

$fulfills = array_column($arr, 'Fulfill');
$avg = array_sum($fulfills) / count($fulfills);

CodePudding user response:

You can then divide that sum by the number of occurrences of the key to get the average.

Here's an example of how you can do this:

function calculateAverage(array $arr, string $key): int|float {
    $values = array_column($arr, $key);
    return array_sum($values) / count($values);
}

echo calculateAverage([], 'Fulfill');
  •  Tags:  
  • php
  • Related