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
?
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).
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.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With