简体   繁体   中英

How can I sort an array by two criteria?

I have an array I want to echo alphabetized while ignoring the number that starts each string, as such:

0 Apple
1 Apple
3 Apple
0 Banana
1 Banana
0 Carrot
//...

When I sort, the number is sorted first. So, I've tried asort, sort_string with no success.

$file = file("grades.txt");
asort($file, SORT_STRING);

Can I look only at the alphabet characters and ignore numbers? Or can I ignore the first character and sort starting with the second character? What should I do to get the above result?

It would be great if the numbers could be in order AFTER the arrays are echoed alphabetically, but it is not demanded if too difficult to do.

Maybe try php's uasort function. http://php.net/manual/en/function.uasort.php

function cmp($a, $b) {
    if ($a[2] == $b[2]) {
        return 0;
    }
    return ($a[2] < $b[2]) ? -1 : 1;
}
uasort($array, 'cmp');

You can swap the position of the alphabetic part and numeric part, and use strcmp() to compare the string in usort() .

http://php.net/manual/en/function.usort.php

usort($arr, function($a, $b) {
    $a = $a[2].' '.$a[0];
    $b = $b[2].' '.$b[0];
    return strcmp($a, $b);
});

For this you need a custom order function, which you can do with uasort() , eg

Simply explode() your string by a space and save the number and the string in a variable. Then if string is the same order the elements by the number. Else sort by the string.

uasort($arr, function($a, $b){
    list($numberA, $stringA) = explode(" ", $a);
    list($numberB, $stringB) = explode(" ", $b);

    if(strnatcmp($stringA, $stringB) == 0)
        return $numberA < $numberB ? -1 : 1;
    return strnatcmp($stringA, $stringB);    

});

You can use preg_replace() to remove numbers from beginning of strings, preg_replace() accepts third param ( subject ) as an array ( the search and replace is performed on every item ).

$file = preg_replace( '/^[\d\s]+/', '', file("grades.txt") );

arsort( $file );

EDIT:

Use preg_replace( '/^([\\d\\s]+)(.+)/', '$2 $1', file("grades.txt") ) to shift the numbers to the end of string.

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