Mardoxx Posted July 31, 2009 Share Posted July 31, 2009 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! Quote Link to comment https://forums.phpfreaks.com/topic/168222-solved-how-to-group-numeric-data-that-is-in-an-array/ Share on other sites More sharing options...
.josh Posted July 31, 2009 Share Posted July 31, 2009 $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; } Quote Link to comment https://forums.phpfreaks.com/topic/168222-solved-how-to-group-numeric-data-that-is-in-an-array/#findComment-887356 Share on other sites More sharing options...
Mardoxx Posted July 31, 2009 Author Share Posted July 31, 2009 wow! it looks so simple thank you ! Quote Link to comment https://forums.phpfreaks.com/topic/168222-solved-how-to-group-numeric-data-that-is-in-an-array/#findComment-887462 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.