[Solved] PHP average by group of n elements in an array


First of all, you should redesign your data structure. You aggregate the values in strings in $values and then it’s difficult to extract and use the individual components.

$values = array();
for($i=1;$i<=$arrayCount;$i++){
    $date = trim($allDataInSheet[$i]["A"]);
    $dir = trim($allDataInSheet[$i]["B"]);
    $sinvalue= sin(deg2rad($dir));
    $cosvalue= cos(deg2rad($dir));            
    $values[] = array(
        'date' => $date,
        'sin'  => $sinvalue,
        'cos'  => $cosvalue,
    );
}

Now, several array functions can be applied to do the job.

PHP does not provide a function to compute the average for a list of numbers but it is not difficult to write one:

function average(array $input)
{
    return array_sum($input) / count($input);
}

Extract the values associated to 'sin' in $values, split the list in chunks of 5 items, apply the function average() to each chunk. The result is a list of 288 values.

$avg288 = array_map(
    'average',
    array_chunk(
        array_column($values, 'sin'),
        5
    )
);

Similar to above, split the list of 288 averages into 24 chunks of 12 values, apply average() to each chunk, get a list of 24 numbers.

$avg24 = array_map(
    'average',
    array_chunk(
        $avg288,
        12
    )
);

Read about array_sum(), count(), array_column(), array_chunk(), array_map().


Update

On PHP 5.4 array_column() doesn’t work (because it was introduced in PHP 5.5.).

In this case you can compute the array returned by array_column() in the initial loop, where $values is created:

$values = array();
$sins = array();
for($i=1;$i<=$arrayCount;$i++){
    $date = trim($allDataInSheet[$i]["A"]);
    $dir = trim($allDataInSheet[$i]["B"]);
    $sinvalue= sin(deg2rad($dir));
    $cosvalue= cos(deg2rad($dir));            
    $values[] = array(
        'date' => $date,
        'sin'  => $sinvalue,
        'cos'  => $cosvalue,
    );
    $sins[] = $sinvalue;
}

The use $sins instead of array_column($values, 'sin') in the computation of $avg288.

6

solved PHP average by group of n elements in an array