Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.