Reduce the size of a numeric array by averaging values ​​in PHP: 20 values ​​=> X values

In PHP, I have an array containing 20 elements or more. Keys are assigned automatically. Values ​​are random numbers from 1 to 50.

<?php
$randomList = array();
for ($i = 0; $i < 20; $i++) {
  $randomList[] = mt_rand(1, 50);
}
?>

Now I want to build this array in a line chart. Unfortunately, I can only use 5 points for the graph. Therefore, I have to reduce the number of elements in the array. But I do not want the appearance of the chart to change. So I need a function like this:

To make it clear: when I want to reduce the size of the array from 6 elements to 3 elements, I can simply sum the pairs of two elements each and take the average value:

array (1, 8, 3, 6, 9, 5) => array (4.5, 6, 7)

My function should do this with variable sizes (for input and output).

, . !

+3
2

"" $randomList $X , array_chunk() array_map() :

$randomList = array_chunk($randomList, count($randomList) / $X);
$randomList = array_map('array_average', $randomList);

array_average() :

function array_average($array) {
    return array_sum($array) / count($array);
}
+4
$randomList = array();
for ($i = 0; $i < 20; $i++) {
  $randomList[] = mt_rand(1, 50);
}  

$avgList=array();
for($i=0;$i<count($randomList)/2;$i++) {
   $avgList[] = ($randomList[$i*2] + $randomList[$i*2+1]) / 2
}
-1

Source: https://habr.com/ru/post/1713907/


All Articles