简体   繁体   中英

How to Sort array alphabetical and by strlen

I am looking for the cleanest ways to sort array alphabetically and by strlen in PHP. The cleanest way i came up with to sort by strlen is this:

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. The array keys are not needed after sort.

You can also use 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).

There will be no tie in sort() or natsort() that will be "broken" by using strlen() .

The answer is: Don't bother with strlen() as a second comparison and usort() is overkill.

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',
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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