fraser5002 Posted April 5, 2010 Share Posted April 5, 2010 Hi , Is there any simple function in PHP that will allow me to sort an array of numbers base on how close they are to a predifined number say x = 0.1 , 0.4 , 0.6 , 0.7 , 0.8 performing a sort on values cloest to 0.5 would give 0.4, 0.6 , 0.7 , 0.8, 0.1 ???? Is there an easy way to do this in PHP? Link to comment https://forums.phpfreaks.com/topic/197619-sort-closest-to-a-declared-value/ Share on other sites More sharing options...
the182guy Posted April 5, 2010 Share Posted April 5, 2010 I don't know if there is already a function to do that, but if not then you can write your own. For example: function doSort($list, $number) { $temp = array(); $out = array(); foreach($list as $num) { if($number >= $num) { $difference = $number - $num; } elseif($number < $num) { $difference = $num - $number; } $temp["$num"] = $difference; } asort($temp); $out = array_keys($temp); return $out; } Use it like this, just pass in the array of numbers, and the target number like $list = array(0.1, 0.4, 0.6, 0.7, 0.; $sorted = doSort($list, 0.5); print_r($sorted); // prints Array ( [0] => 0.4 [1] => 0.6 [2] => 0.7 [3] => 0.8 [4] => 0.1 ) Link to comment https://forums.phpfreaks.com/topic/197619-sort-closest-to-a-declared-value/#findComment-1037142 Share on other sites More sharing options...
Mchl Posted April 5, 2010 Share Posted April 5, 2010 Or use usort/uasort function compare($a, $b) { if(abs($a-0.5) > abs($b-0.5)) { return 1; } if(abs($a-0.5) < abs($b-0.5)) { return -1; } return 0; } usort($array,'compare'); and if you have PHP >=5.3 you can use closures for more flexibility: $zeroPoint = 0.5; usort($array,function($a, $b) { if(abs($a-$zeroPoint) > abs($b-$zeroPoint)) { return 1; } if(abs($a-$zeroPoint) < abs($b-$zeroPoint)) { return -1; } return 0; }); Link to comment https://forums.phpfreaks.com/topic/197619-sort-closest-to-a-declared-value/#findComment-1037175 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.