First of all I am new in php. I need help to sort an array.
I have an array of ID’s and zip codes like this:
JavaScript
x
Array (
[2286] => 3150-259
[2284] => 3040-256
[2282] => 5430-659
[2280] => 2560-270
[2278] => 3740-271
[2276] => 2495-401 and so on
)
Now I have a number lets say ‘2900’ I would like to sort my array from the closest number (2900) to the most distant.
Example: the number is 2900. So the array should sort like this:
JavaScript
Array (
[2284] => 3040-256
[2286] => 3150-259
[2280] => 2560-270
[2276] => 2495-401
[2282] => 5430-659 and so on
Can someone help me?
Thank you
Advertisement
Answer
I guess, you can use function uksort in next way:
JavaScript
<?php
$arr = [
2286 => "3150-259",
2284 => "3040-256",
2282 => "5430-659",
2280 => "2560-270",
2278 => "3740-271",
2276 => "2495-401",
];
$n = 2900;
uksort($arr, function ($a, $b) use ($n) {
return (abs($a-$n) >= abs($b-$n)) ? 1 : -1;
});
var_export($arr);