在PHP中使用uasort访问阵列关键 [英] Access array key using uasort in PHP
问题描述
如果在PHP中一个相当基本的 uasort
函数如下:
uasort($ ARR,函数($ A,$ B){
如果($ A> $ B)
返回-1;
如果($ A< $ B)
返回1;
...
}
我想排序如下所示的数组:
{[1642] => 1,[9314] => 4,[1634] => 3 ...}
它包含有我的主要标准比较整数。但是,如果整数是相等的,那么我想访问他们的键值中, uasort
函数中,并做一些魔法与它从那里找出排序。
我不知道该怎么做,因为它似乎 $ A
和 $ B
变量得到传递给函数仅仅是整数,没有相应的密钥,但因为我用实际preserve按键功能应该有访问密钥以及一种方式。任何想法?
uksort($ ARR,函数($ A,$ B)使用($ ARR){
返回$常用3 [$ A] - $改编[$ B]:$ A - $ B;
});
您可以通过键获取值,所以使用 uksort
这给你钥匙。替换 $ A - $ B
与适当的法宝,在这里它只是由键值排序
If have a rather basic uasort
function in PHP that looks like this:
uasort($arr, function($a, $b) {
if ($a > $b)
return -1;
if ($a < $b)
return 1;
...
}
The array I'm trying to sort looks like the following:
{[1642] => 1, [9314] => 4, [1634] => 3 ...}
It contains integers that are my main comparison criteria. However, if the integers are equal, then I would like to access their key values, inside the uasort
function and do some magic with it to figure out the sorting from there.
I have no clue how to do that as it seems that the $a
and $b
variables that get passed into the function are just the integers without the corresponding keys but there should be a way to access the key as well since I'm using a function to actually preserve the keys. Any ideas?
uksort($arr, function ($a, $b) use ($arr) {
return $arr[$a] - $arr[$b] ?: $a - $b;
});
You can get the values by the keys, so use uksort
which gives you the keys. Replace $a - $b
with your appropriate magic, here it's just sorting by the key's value.
这篇关于在PHP中使用uasort访问阵列关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!