PHP的排序由predefined为了一个数组 [英] php sorting an array by predefined order
问题描述
我挣扎试图理清通过正常功能的数组,我敢肯定,这需要自定义比较功能,但没有少会扔了这一点那里。
I'm struggling trying to sort an array via the normal functions, i'm sure this needs a custom comparison function but none the less will chuck this out there.
我有里面5元素的数组。我想阵列本身像这样排序,arsort差一点但并不完全:
I have an array with 5 elements inside it. I would like the array to sort itself like so, arsort came close but not quite:
4,0,1,2,3
4,0,1,2,3
只是为了澄清,数组一样的位置:$数组[0];
Just to clarify, the position of the array like: $array[0];
我还没有实际的阵列比较功能显得之前,因此在正确的方向一推将是最有帮助的解决这个!
I haven't actually looked at array comparison functions before, so a push in the right direction would be most helpful to solve this!
谢谢,
亚当
推荐答案
此方法将使用密钥的pre定义的顺序使用数组排序uksort
This method will sort an array using a pre-defined order of keys using uksort
$desiredIndexOrder = array(4 => 1, 0 => 2, 1 => 3, 2 => 4, 3 => 5);
uksort($inputArray, function($a, $b) use ($desiredIndexOrder) {
return $desiredIndexOrder[$a] > $desiredIndexOrder[$b] ? -1 : 1;
});
注意 $ desiredIndexOrder
阵列在指数=>所需的排序位置
格式。如果你不想把你的数组中的格式,你可以把它用这个为你打造的:
Notice the $desiredIndexOrder
array is in index => desired sort position
format. If you don't want to put your array in that format, you can have it built for you using this:
$desiredIndexOrder = array();
foreach ($desiredKeyOrder as $position=>$key) {
$desiredIndexOrder[$key] = $position + 1;
}
其中, $ desiredKeyOrder
是键的排列顺序为:阵列(4,0,1,2,3)
这篇关于PHP的排序由predefined为了一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!