You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按距离用户最近排序PHP中的Paysera自提柜数组?

按用户坐标排序Paysera自提柜数组

问题背景

我拥有一组Paysera自提柜数据数组:

$lockers = [
    [
        'id' => 'PMFOzGmlcQ-9GmEt5vj9JTGals_1nI87Lm',
        'shipment_gateway_code' => 'lp',
        'code' => '0199',
        'address' => [
            'country' => 'LT',
            'city' => 'Vilnius',
            'street' => 'Žirmūnų g. 48A',
            'postal_code' => '09226'
        ],
        'coordinates' => [
            'latitude' => 54.70274,
            'longitude' => 25.30368
        ],
        'location_name' => 'Express Market',
        'enabled' => 1
    ],
    [
        'id' => 'PMBBGl0TsF1vuv8YqeLsn4gyWwGB9-vd98',
        'shipment_gateway_code' => 'lp',
        'code' => '0198',
        'address' => [
            'country' => 'LT',
            'city' => 'Vilnius',
            'street' => 'Lazdynėlių g. 23',
            'postal_code' => '04126'
        ],
        'coordinates' => [
            'latitude' => 54.66283,
            'longitude' => 25.19253
        ],
        'location_name' => 'Maxima',
        'enabled' => 1
    ]
];

同时有用户的坐标数组:

$userCoords = [
    'latitude' => 54.70274,
    'longitude' => 25.30368
];

需要将自提柜数组按离用户最近的顺序排序,但尝试的代码完全无效:

$cities = <your array>;

$point = array(
    'latitude' => 50.6000,
    'longitude' => -74.15000
);

function distance($a, $b) {
    return sqrt(
        pow($a['latitude'] - $b['latitude'], 2)
        + pow($a['longitude'] - $b['longitude'], 2));
}

usort($cities, function($p, $q) {
    global $point;
    return distance($p, $point) - distance($q, $point);
});

修复方案

原代码失效的核心原因:

  • 坐标路径错误:自提柜的坐标存储在coordinates子数组中,原代码直接取$a['latitude']无法获取正确值。
  • 变量传递不规范:使用global容易引发作用域冲突,改用闭包的use语法更可靠。

额外优化:排序时无需计算实际距离(开根号),比较平方距离即可,能减少计算开销。

修复后的完整代码:

// 计算两点间的平方距离(用于排序比较,无需开根号)
function calculateSquaredDistance($lockerCoords, $userCoords) {
    $latDiff = $lockerCoords['latitude'] - $userCoords['latitude'];
    $lonDiff = $lockerCoords['longitude'] - $userCoords['longitude'];
    return pow($latDiff, 2) + pow($lonDiff, 2);
}

// 按离用户由近到远排序自提柜数组
usort($lockers, function($lockerA, $lockerB) use ($userCoords) {
    $distA = calculateSquaredDistance($lockerA['coordinates'], $userCoords);
    $distB = calculateSquaredDistance($lockerB['coordinates'], $userCoords);
    return $distA - $distB;
});

// 输出排序后的结果
print_r($lockers);

运行后,与用户坐标完全重合的Express Market自提柜会排在第一位,Maxima自提柜排在第二位。

内容的提问来源于stack exchange,提问作者Viacheslav Ravdin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 16:05:01