我在对如下所示的简单数组进行排序时遇到了一些困难:
array(4) {
[32]=>
string(1) "1"
[34]=>
string(1) "2"
[35]=>
string(1) "1"
[33]=>
string(1) "0"
}
我只想按索引对其进行排序,因此它看起来像这样:
array(4) {
[32]=>
string(1) "1"
[33]=>
string(1) "0"
[34]=>
string(1) "2"
[35]=>
string(1) "1"
}
我尝试使用 sort($votes);
但这似乎删除了索引,之后我的数组看起来像这样:
array(4) {
[0]=>
string(1) "0"
[1]=>
string(1) "1"
[2]=>
string(1) "1"
[3]=>
string(1) "2"
}
那么,什么是对这个数组进行排序的最佳方式,以便索引仍然相同,但已排序?
最佳答案
您想使用 ksort()
,它按键对数组进行排序。
ksort
Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.
关于php - 按索引对 php 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7925909/