如何订购这个棘手的PHP关联数组?

时间:2022-09-26 08:21:48

How to order this tricky PHP associative array?

如何订购这个棘手的PHP关联数组?

I have this associative array:

我有这个关联数组:

Array (
    [4] => 3
    [2] => 4
    [3] => 1
    [6] => 1
    [1] => 1
)

I need to order it by key with highest value, BUT I also need to keep the keys with the same values in their original order, so it needs to come out to:

我需要通过具有最高值的键来订购它,但我还需要按原始顺序保持键具有相同的值,因此它需要出现:

Array (
    [2] => 4
    [4] => 3
    [3] => 1
    [6] => 1
    [1] => 1
    )

I cannot use arsort() because it rearranges the keys with the same value based on the key's numeric order, I'm really at a loss here! Any suggestions?

我不能使用arsort()因为它根据键的数字顺序重新排列具有相同值的键,我真的在这里不知所措!有什么建议么?

1 个解决方案

#1


4  

natsort to rescue:

natsort救援:

$blub = array(4 => 3, 2 => 4, 3 => 1, 6 => 1, 1 => 1);
natsort($blub);
$blub = array_reverse($blub, true);

var_dump($blub);

This will always output:

这将始终输出:

array(5) { [2]=> int(4) [4]=> int(3) [3]=> int(1) [6]=> int(1) [1]=> int(1) }

natsort seems to be using a different sorting algorithm which luckily preserves the order when the values are the same as opposed to asort. Note however that natsort might be slightly slower than the other traditional sorting functions because of this.

natsort似乎使用了一种不同的排序算法,当值与asort相反时,幸运地保留了顺序。但请注意,由于这个原因,natsort可能比其他传统的排序函数稍慢。

#1


4  

natsort to rescue:

natsort救援:

$blub = array(4 => 3, 2 => 4, 3 => 1, 6 => 1, 1 => 1);
natsort($blub);
$blub = array_reverse($blub, true);

var_dump($blub);

This will always output:

这将始终输出:

array(5) { [2]=> int(4) [4]=> int(3) [3]=> int(1) [6]=> int(1) [1]=> int(1) }

natsort seems to be using a different sorting algorithm which luckily preserves the order when the values are the same as opposed to asort. Note however that natsort might be slightly slower than the other traditional sorting functions because of this.

natsort似乎使用了一种不同的排序算法,当值与asort相反时,幸运地保留了顺序。但请注意,由于这个原因,natsort可能比其他传统的排序函数稍慢。