Jump to content

[SOLVED] How to group numeric data that is in an array?


Mardoxx

Recommended Posts

I have an array of numbers which can be in any order:

$number_array = array(1, 6, 9, 6.1, 3, 2);

and a limit to which i want to capture the data.

$limit = 0.5;

 

How can I group the data so that data within +- $limit and it looks like so:

 

$output[0] = array(1, 1.5);
$output[1] = array(6, 6.1);
$output[2] = array(9);
$output[3] = array(2);

 

 

I just can't think of a way of doing it....

Unless I order the array first then compare the next result and

if ($next - $current > 0.5) { //Put into new array } else { //Put into current array}

But even then I don't know how to execute the code to put it into the correct array...

 

Can anyone shed some light on it?

 

Thanks!

$number_array = array(1, 6, 9, 6.1, 3, 2);
$limit = 0.5;

sort($number_array);
foreach($number_array as $k => $n) {
  $diff = ($number_array[$k-1]) ? ($n - $number_array[$k-1]) : 0;
  if ($diff > $limit) $p++;
  $result[$p][] = $n;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.