3

In PHP I have an array containing 20 elements or more. The keys have been assigned automatically. The 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 plot this array into a line chart. Unfortunately, I can only use 5 points for the graph. So I must reduce the number of elements in the array. But I don't want the look of the chart to be changed. So I need a function like this:

To make it clearer: When I want to reduce the size of an array from 6 elements to 3 elements, I can just sum up pairs of two elements each and take the average:

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

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

I hope you can help me. Thanks in advance!

4

2 回答 2

4

要以您所描述的方式将数组“缩短”$randomList为元素,您可以像这样一起使用array_chunk()array_map()$X

$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);
}
于 2009-07-29T22:45:41.077 回答
-1
$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
}
于 2009-07-29T22:46:46.737 回答