php - 按索引对 php 数组进行排序

标签 php arrays sorting

我在对如下所示的简单数组进行排序时遇到了一些困难:

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/

相关文章:

php - 从 php 文件运行命令时出现 SQL 错误

java - 以数组形式返回日历事件详细信息

Powershell - 使用特殊字符对字符串对象进行排序

python - 从第三个数组中的两个数组中有效地获取每对元素的最小值

ios - 使用 firebase 在 tableview 中显示数据

javascript - 如何在数组中搜索某个值,如果找到 2 个或更多值,则仅删除其中一个值?

sorting - unix sort -n -t","给出意外结果

php - 如何将变量从php模板传递给javascript

允许转换为 sql 的 PHP 规范模式

php - MySQL 事务 - 开始问题