简体   繁体   English

仅按数字排序数组

[英]sort array numerically only

This is the array 这是数组

$array = array(
   'list[P] = 1',
   'list[A] = 1',
   'list[F] = 2',
   'list[B] = 1'
);


This is the output I want 这是我想要的输出

[0] => list[P] = 1
[1] => list[A] = 1
[2] => list[B] = 1
[3] => list[F] = 2


notice list[P] remains at the top because it is the first with value 1. So only numeric sorting 注意list[P]保持在顶部,因为它是第一个带有值1的列表。因此,仅数字排序

Try taking a look at this documentation . 尝试看一下本文档

As you are trying to sort a specific part of the value, then you need to write your own comparator, and therefore the only method available is the usort function. 当您尝试对值的特定部分进行排序时,您需要编写自己的比较器,因此唯一可用的方法是usort函数。

The uksort function takes two attributes, the array and the method name that you wish to use to do your comparison. uksort函数具有两个属性,即您希望用来进行比较的数组和方法名称。 You then write this method, which takes two values as a parameters, and return a true of false, depending on whether it is greater than or less than. 然后编写此方法,该方法将两个值用作参数,并根据是大于还是小于返回true或false。

Therefore, you would have to substring the values coming in, to only compare the numbers. 因此,您必须对输入的值进行子字符串化,以便仅比较数字。

The following code sample seems to work 以下代码示例似乎有效

function cmp($a, $b)
{
    $a = substr($a, -1);
    $b = substr($b, -1);
    return $a >= $b;
}

$array = array(
   'list[P] = 1',
   'list[A] = 1',
   'list[F] = 2',
   'list[B] = 1'
);

usort($array, "cmp");

var_dump($array);

The same code, only using PHP's anonymous function: 相同的代码,仅使用PHP的匿名函数:

$array = array(
   'list[P] = 1',
   'list[A] = 1',
   'list[F] = 2',
   'list[B] = 1'
);

usort(
   $array,
   function ($a, $b){
      $a = substr($a, -1);
      $b = substr($b, -1);
      return $a >= $b;
   }
);

var_dump($array);

If it is important to preserve records or keys with equal values in the same order they were input into the sort in the software you are writing then you would need a sort algorithm or method which is categorised as 'stable'. 如果重要的是保存具有相等值的记录或键,其顺序应与输入到您正在编写的软件中的排序顺序相同,那么您将需要一种归类为“稳定”的排序算法或方法。 This limits the types of sort methods available to a programmer in any one country or a region within it in order to conform to the relevant rules. 这限制了其中任何一个国家或地区的程序员可以使用的排序方法的类型,以符合相关规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM