按索引排序php数组 [英] sort php array by index

查看:65
本文介绍了按索引排序php数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在整理一个像这样的简单数组时遇到了一些困难:

I'm having some difficulties sorting a simple array that looks like this:

array(4) {
  [32]=>
  string(1) "1"
  [34]=>
  string(1) "2"
  [35]=>
  string(1) "1"
  [33]=>
  string(1) "0"
}

我只想按索引对它进行排序,所以它看起来像这样:

I just want to sort it by the index so it would look like this:

array(4) {
  [32]=>
  string(1) "1"
  [33]=>
  string(1) "0"
  [34]=>
  string(1) "2"
  [35]=>
  string(1) "1"
}

我尝试使用sort($votes);,但这似乎删除了索引,之后我的数组如下所示:

I tried using sort($votes); but this seems to remove the index and my array looks like this afterwards:

array(4) {
  [0]=>
  string(1) "0"
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "1"
  [3]=>
  string(1) "2"
}

那么对数组进行排序以使索引仍然相同但已排序的最佳方法是什么?

So what would be the best way of sorting this array so that the index is still the same, but sorted?

推荐答案

您要使用 ksort() ,按其键对数组进行排序.

You want to use ksort(), which sorts an array by its keys.

ksort

按键对数组进行排序,从而保持与数据相关的键.这是 主要用于关联数组.

ksort

Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.

这篇关于按索引排序php数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆