executable
executable

Reputation: 3600

Count number of occurrences of a key in a multidimensional array

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

Upvotes: 0

Views: 175

Answers (2)

Foobar
Foobar

Reputation: 809

Just one line more:

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

Upvotes: 1

Barmar
Barmar

Reputation: 780974

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);

Upvotes: 1

Related Questions