Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array by the distance to a number

For example if you have a set of numbers 5,4,3,2,1 and you want all numbers ordered by closest to 3 the result would be 3,2,4,5,1.

I've tried using uasort and written a custom sort function to take the fixed digit(3 in this case), but it didn't work. I wrote the function to take the fixed digit away from the current two digits being compared and applied abs to them.

I need a way where I can compare which number of comparing how close the current number being accessed is and to slot it in the right place in the array.

Any ideas? Can this be achieved using uasort?

like image 870
jdawg Avatar asked Sep 17 '15 10:09

jdawg


People also ask

How do you sort an array by distance?

sort(function(a,b) { return parseFloat(a. distance) - parseFloat(b. distance) } ); However this only sorts values by distance and displays the other values of lists as it is like address,type (i.e it shows distance of some other address to some another address after sorting).

How do you sort an array by value?

PHP - Sort Functions For Arrays sort() - sort arrays in ascending order. rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key.

How do you sort an array by smallest to largest?

The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.


1 Answers

uasort() is already a good start. Now you just have to use the distance to 3 as criteria to sort your array:

number   | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
---------------------------------------
distance | 3 | 2 | 1 | 0 | 1 | 2 | 3 | 

Code:

uasort($arr, function($a, $b){
    return abs(3-$a) - abs(3-$b);
});
like image 62
Rizier123 Avatar answered Nov 07 '22 07:11

Rizier123