简体   繁体   English

如何对以给定数字表示的数组进行排序

[英]How can I sort an array stating in a given number

First of all I am new in php.首先,我是 php 的新手。 I need help to sort an array.我需要帮助来对数组进行排序。

I have an array of ID's and zip codes like this:我有一组 ID 和 zip 代码,如下所示:

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.现在我有一个数字让我们说“2900”我想将我的数组从最近的数字(2900)排序到最远的数字。

Example: the number is 2900. So the array should sort like this:示例:数字是 2900。所以数组应该像这样排序:

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谢谢

I guess, you can use function uksort in next way:我想,你可以使用 function uksort在下一个方式:

<?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);

Check PHP code here 在此处检查 PHP 代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM