How to get average of an associative array in php

I have a multidimensional associative array of students ‘name’ and ‘time’:

Now, I want to find the average time for each student:

Capture
Output: `array:3 [▼
4 => array:4 [▼
0 => {#891
+“id”: 4
+“reftime”: “748”
+“user_names”: “Musiri muscifique”
}
3 => {#896 :arrow_forward:}
5 => {#900 :arrow_forward:}
9 => {#908 :arrow_forward:}
]
7 => array:5 [:arrow_forward:]
6 => array:1 [▼
8 => {#907
+“id”: 6
+“reftime”: “748”
+“user_names”: “Bruno Gisa”
}
]
]

 $arr = array(); 

    foreach($Datas as $key => $item)
    {
        $arr[$item->id][$key] = $item; 
    }`

I would like to have the following result

    $studentNames =['Musiri muscifique','John','AnnY'];
    $studentAverageTimes =['540','210','200'];

Please how can get it?
Thanks

You need to loop over your array, getting the name from one of the records and building the average of all reftimes in the user’s data. I’ve split out the averaging code into a separate function below; that’s not required, but makes things easier to follow.

$studentNames = [];
$studentAverageTimes = [];

foreach ($data as $studentData) {
    // there may not be any data against a record.
    // If so, skip to the next student.
    if (empty($studentData)) {
        continue;
    }

    $studentNames[] = $studentData[0]['user_names'];
    $studentAverageTimes[] = averageRefTimes($studentData);
}

function averageRefTimes($studentData)
{
    $countEntries = 0;
    $sumEntries = 0;

    foreach ($studentData as $dataItem) {
        $countEntries ++;
        $sumEntries += $dataItem['reftime'];
    }

    return $sumEntries / $countEntries;
}
1 Like

Thank you, this is helpful solution

Sponsor our Newsletter | Privacy Policy | Terms of Service