我已经根据值距离从低到高对多维数组进行了排序。这是输出的一个示例:(实际输出大约有 20 或 30 个数组)。
数组 (
[0] => Array
(
[id] => 1
[distance] => 5
[sponsor] => 0
)
[1] => Array
(
[id] => 20
[distance] => 8
[sponsor] => 1
)
[2] => Array
(
[id] => 25
[distance] => 10
[sponsor] => 0
)
[3] => Array
(
[id] => 78
[distance] => 25
[sponsor] => 1
)
)
在从低到高对距离进行排序后,如果赞助商 = 1,我想优先考虑。这是首选输出:
数组 (
[0] => Array
(
[id] => 20
[distance] => 8
[sponsor] => 1
)
[1] => Array
(
[id] => 78
[distance] => 25
[sponsor] => 1
)
[2] => Array
(
[id] => 1
[distance] => 5
[sponsor] => 0
)
[3] => Array
(
[id] => 25
[distance] => 10
[sponsor] => 0
)
)
发起人为 0 或 1。我该如何解决这个问题?我在想,在对距离进行排序之前,我应该根据 sponsor (0,1) 将数组分成 2 个数组,按距离对两个数组进行排序,然后将它们与新多维数组顶部的 sponsor=1 合并。这是这样做的方法吗?
感谢您的投入。
这是 usort 建议的略微修改版本。假设源数组被调用$arr:
usort(
$arr, function($a, $b) {
if ( $a['sponsor'] == $b['sponsor'] ) {
if ( $a['distance'] == $b['distance'] ) {
return 0;
}
return $a['distance'] < $b['distance'] ? -1 : 1;
}
return $a['sponsor'] > $b['sponsor'] ? -1 : 1;
}
);
您必须将原始数组拆分为 2 个数组:第一个有 sponsor=1
个数组,第二个数组有 sponsor=0
个数组。然后分别对它们进行排序并合并。
不知何故像这样:
$array1 = array_filter($array, function ($v) { return $v['sponsor'] == 1; });
$array2 = array_filter($array, function ($v) { return $v['sponsor'] == 0; });
function cmp($a, $b) {
return $a['distance'] < $b['distance']? -1 : 1;
}
usort($array1, cmp);
usort($array2, cmp);
$result = array_merge($array1, $array2);
您可以使用 array_multisort() 函数来实现您想要的:
<?php
$arr = [
['id' => 1, 'distance' => 5, 'sponsor' => 0],
['id' => 20, 'distance' => 8, 'sponsor' => 1],
['id' => 25, 'distance' => 10, 'sponsor' => 0],
['id' => 78, 'distance' => 25, 'sponsor' => 1],
];
$sponsor = array_column($arr, 'sponsor');
$distance = array_column($arr, 'distance');
// rearrange $arr by sponsor DESC and then by distance ASC
array_multisort($sponsor, SORT_DESC, $distance, SORT_ASC, $arr);
print_r($arr);
这将有效,但是如果您使用稳定的排序算法,那么您可以先按距离排序,然后按赞助商降序排序,您将获得所需的结果。
试试这个:
<?php
$ar = array(
array("10", 11, 100, 100, "a"),
array( 1, 2, "2", 3, 1)
);
array_multisort($ar[0], SORT_ASC, SORT_STRING,
$ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>
或
<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);
var_dump($ar1);
var_dump($ar2);
?>