简体   繁体   English

如何按字母顺序和 strlen 对数组进行排序

[英]How to Sort array alphabetical and by strlen

I am looking for the cleanest ways to sort array alphabetically and by strlen in PHP.我正在寻找在 PHP 中按字母顺序和 strlen 对数组进行排序的最干净的方法。 The cleanest way i came up with to sort by strlen is this:我想出的按 strlen 排序的最干净的方法是:

array_multisort(array_map('strlen', $array), $array);

How would i extend this to sort alphabetically by values as the primary sorting?我如何将其扩展为按值按字母顺序排序作为主要排序?

This is an example array:这是一个示例数组:

array('name'=>'Firstname','name2'=>'Lastname1','name3'=>'Lastname2')

The order after the sort function is not important, what is important is that it always returns the same order when sorted, regardless the same length of some values. sort 函数后面的顺序并不重要,重要的是排序时总是返回相同的顺序,而不管某些值的长度相同。 The array keys are not needed after sort.排序后不需要数组键。

You can also use usort() :您还可以使用usort()

$your_array = array( . . . );
$your_compare_function = function($elem1, $elem2) {
    return strlen($elem1) > strlen($elem2) || $elem1 > $elem2;
};

usort($your_array, $your_compare_function);

If the sort order is incorrect, I apologize.如果排序不正确,我深表歉意。 I'm not sure from your post what the intended ordering is.我从你的帖子中不确定预期的顺序是什么。 Just update the compare function accordingly.只需相应地更新比较功能。

You either want sort() or natsort() (if you are dealing with multi-digit numbers in your strings).您需要sort()natsort() (如果您要处理字符串中的多位数字)。

There will be no tie in sort() or natsort() that will be "broken" by using strlen() . sort()natsort()不会有使用strlen()被“破坏”的关系。

The answer is: Don't bother with strlen() as a second comparison and usort() is overkill.答案是:不要用strlen()作为第二个比较而烦恼,而usort()是矫枉过正。

Code: ( Demo )代码:( 演示

$array=['name'=>'Firstname','name2'=>'Lastname10','name3'=>'Lastname2','name4'=>'Lastname1','name4'=>'Lastname20'];
natsort($array);
var_export($array);

echo "\n---\n";

sort($array);
var_export($array);

Output:输出:

array (
  'name' => 'Firstname',
  'name3' => 'Lastname2',
  'name2' => 'Lastname10',
  'name4' => 'Lastname20',
)
---
array (
  0 => 'Firstname',
  1 => 'Lastname10',
  2 => 'Lastname2',
  3 => 'Lastname20',
)

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

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