所以我有相当大的数据数组,需要按两个标准对它们进行排序。
有变数$data['important']
and $data['basic']
.
它们是简单的数字,我使用 uasort 进行排序$data
首先按重要,然后按基本。
So
Important | Basic
10 | 8
9 | 9
9 | 7
7 | 9
usort 函数很简单
public function sort_by_important($a, $b) {
if ($a[important] > $b[important]) {
return -1;
}
elseif ($b[important] > $a[important]) {
return 1;
}
else {
return 0;
}
}
如何将数组重新排序为第二个变量并保持重要顺序?
感谢大家。
EDIT
在这之后添加第三个排序选项怎么样?非常重要 > 基本 > 更少
你真的应该使用array_multisort()
,
// Obtain a list of columns
foreach ($data as $key => $row) {
$important[$key] = $row['important'];
$basic[$key] = $row['basic'];
}
array_multisort($important, SORT_NUMERIC, SORT_DESC,
$basic, SORT_NUMERIC, SORT_DESC,
$data);
但如果你必须使用usort()
:
public function sort_by_important($a, $b) {
if ($a[important] > $b[important]) {
return -1;
} elseif ($b[important] > $a[important]) {
return 1;
} else {
if ($a[basic] > $b[basic]) {
return -1;
} elseif ($b[basic] > $a[basic]) {
return 1;
} else {
return 0;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)