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
  • 1
    Hi. Can you be more specific about the kind of plot you want to make? Some kind of linear regression? Commented Jul 29, 2009 at 22:42
  • See this example of Google: bit.ly/UFMX5 Assuming I have the "150 data points", I want to have the graph to look like "40 data points". But I don't want to just leave out 73% of the data points. Commented Jul 29, 2009 at 22:45
  • Shouldn't your example result in array(4.5, 4.5, 7) instead of array(4.6, 6, 7)? Commented Jul 29, 2009 at 22:47
  • Oh, yes of course. I thought 3+6 would be 12! :D Really embarrassing. But it's late here in Germany. :) Commented Jul 29, 2009 at 23:25

2 Answers 2

4

To "shorten" an array $randomList to $X elements in the way that you've described, you could use array_chunk() and array_map() together like this:

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

And define array_average() as:

function array_average($array) {
    return array_sum($array) / count($array);
}
Sign up to request clarification or add additional context in comments.

Comments

-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
}

1 Comment

Thanks! But I don't want to halve the array sizes. The function should also be able to reduce an array from 12 elements to 4. Or - even more difficult - 17 elements to 5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.