0

Problem:

I need to sort an numeric array by its distance to an given value. Meaning the numbers closest to the given value, should come first. Performance is not a must, but still appreciated.

Example:

Given I have an array $array = array(1000, 1050, 1100, 1125);.

mySortFunction($array, 1090); should result in array(1100, 1125, 1050, 1000)

TheNish
  • 330
  • 3
  • 15
  • 3
    You brought your homework here. Never bring your homework here. What have you tried so far? – thpl Sep 16 '14 at 13:44
  • Use PHPs built-in `usort()` function. – TiMESPLiNTER Sep 16 '14 at 13:46
  • 1
    `function mySortFunction(&$array, $value) { usort( $array, function ($a, $b) use ($value) { return abs($a - $value) > abs($b - $value); } ); } ` – Mark Baker Sep 16 '14 at 14:07
  • @deceze It's not a duplicate but just a redirection to your question! – Adam Sinclair Sep 16 '14 at 14:10
  • @Shawnley Here's an answer as a comment since it was wrongly flaged as duplicate: function cmp($a, $b) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } function sortArrByDistance(&$arr, $i) { if (!empty($arr)) { foreach ($arr as $key => $value) $tmpArr[$value] = abs($i - $value); uasort($tmpArr, 'cmp'); foreach ($tmpArr as $key => $value) $newArr[] = $key; return $newArr; } else return null; } var_dump(sortArrByDistance($array, 2000)); – Adam Sinclair Sep 16 '14 at 14:12
  • @Adam It's a redirect to the general reference for how to sort arrays. The OP should attempt a solution using that, it usually covers 99% of the problems people have with sorting arrays. Coming up with an appropriate comparison function based on the information given there should be pretty simple. If the OP still needs help with the specifics of such a comparison function, he should make that clear in the question. – deceze Sep 16 '14 at 14:14
  • Mark Baker & Adam Sinclair - Thank you for your help! Though I don't know how to remove the "duplicate" status, so that you can answer. – TheNish Sep 16 '14 at 14:15

0 Answers0