简体   繁体   English

如何按两个条件对数组排序?

[英]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. 因此,我尝试了sort_string,但没有成功。

$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. 也许尝试php的uasort函数。 http://php.net/manual/en/function.uasort.php http://php.net/manual/zh/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() . 您可以交换字母部分和数字部分的位置,并使用strcmp()比较usort()的字符串。

http://php.net/manual/en/function.usort.php http://php.net/manual/zh/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 为此,您需要一个自定义订单函数,可以使用uasort() ,例如

Simply explode() your string by a space and save the number and the string in a variable. 只需用空格将字符串explode()并将数字和字符串保存在变量中即可。 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 ). 您可以使用preg_replace()删除字符串开头的数字, preg_replace()接受第三个参数( subject )作为数组(对每个项目执行搜索和替换)。

$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. 使用preg_replace( '/^([\\d\\s]+)(.+)/', '$2 $1', file("grades.txt") )将数字移到字符串末尾。

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

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