【问题标题】:PHP - array_multisort ? Sorting postal code (zip code)PHP - array_multisort ?排序邮政编码(邮政编码)
【发布时间】:2025-01-14 09:50:02
【问题描述】:

在使用纬度和经度计算两点之间的距离后,我创建了一个如下所示的数组:

$enterprises = array();

//Ex.: Array ( [0] => Array ( [A0A0A0] => 0 ) [1] => Array ( [A0A1A0] => 22.794344863539 ) 
for ($i=0; $i < count($cpEnterprise) ; $i++) {

        $enterprises[] = array($cpEnterprise[$i] => distance($actualCpLat, $actualCpLong, $businessLat[$i], $businessLong[$i], 'k'));

}

主数组包含与其中的实际邮政编码进行比较所需的企业。邮政编码 => 距离。

我需要按从最近到最远的距离对这些内部数组进行排序,我真的不明白 array_multisort 是如何工作的......

【问题讨论】:

  • 你使用$enterprises[] = array($cpEnterprise[$i] =&gt; distance($actualCpLat, $actualCpLong, $businessLat[$i], $businessLong[$i], 'k'))而不是$enterprises[$cpEnterprise[$i]] = distance($actualCpLat, $actualCpLong, $businessLat[$i], $businessLong[$i], 'k')有什么原因吗?第二种方式允许您使用asort
  • @Orangepill 其实没什么好说的。

标签: php postal-code array-multisort


【解决方案1】:

解决这个问题的一个简单方法是重组你的数组并使用 asort

$enterprises = array();

//Ex.: Array ( [0] => Array ( [A0A0A0] => 0 ) [1] => Array ( [A0A1A0] => 22.794344863539 ) 
for ($i=0; $i < count($cpEnterprise) ; $i++) {    
        $enterprises[$cpEnterprise[$i]] = distance($actualCpLat, $actualCpLong, $businessLat[$i], $businessLong[$i], 'k');

}
asort($enterprises);

【讨论】:

  • 它确实有效,谢谢!为什么asort($enterprises) 作用于距离而不是邮政编码?
  • asort 按数组值排序...如果您想按邮政编码(数组的键)排序,您可以使用 ksort。如果您需要它们,arsort 就是您的朋友。
【解决方案2】:

使用array_multisort 取决于您的排序情况。我举个例子,你可能会得到一些线索:

$products_count = array(
  2 => 10,
  5 => 20,
  0 => 13
)

$counts = array();

foreach($products_count as $k => $v)
{
  $counts[$k] = $v;
}

array_multisort($counts, SORT_NUMERIC, SORT_ASC, $products_count);

结果:

array(
  0 => 13,
  2 => 10,
  5 => 20
)

这只是array_multisort 上的一个示例,毫无疑问,您的问题有更多更好的解决方案和答案。

【讨论】: