如何在 PHP 中按字母顺序比较 2 个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1595423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare 2 strings alphabetically in PHP?
提问by Click Upvote
What the title says. Specifically if I have
标题说什么。具体来说,如果我有
$array1['name'] = 'zoo';
$array2['name'] = 'fox';
How can I determine that alphabetically $array2's name should come above $array1's?
我如何确定按字母顺序排列$array2的名称应该在$array1's之上?
回答by aviraldg
Use strcmp. If the first argument to strcmp is lexicographically smaller to the second, then the value returned will be negative. If both are equal, then it will return 0. And if the first is lexicograpically greater than the second then a positive number will be returned.
使用strcmp. 如果 strcmp 的第一个参数按字典顺序小于第二个参数,则返回的值将为负数。如果两者相等,那么它将返回 0。如果第一个在字典上大于第二个,那么将返回一个正数。
nb. You probably want to use strcasecmp(string1,string2), which ignores case...
备注 您可能想使用strcasecmp(string1,string2),它忽略大小写...
回答by Gumbo
回答by JMRC
I'm a little late (then again I wasn't a programmer yet in 2009 :-) No one mentioned this yet, but you can simply use the operators which you use on number as well.
我有点晚了(再说一次,我在 2009 年还不是程序员 :-) 还没有人提到这一点,但是您也可以简单地使用您在数字上使用的运算符。
< > <= >= == !=and more
< > <= >= == !=和更多
For example:
例如:
'a' > 'b'returns false
'a' > 'b'返回 false
'a' < 'b'returns true
'a' < 'b'返回 true
http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/language.operators.comparison.php
IMPORTANT
重要的
There is a flaw, which you can find in the comments below.
有一个缺陷,您可以在下面的评论中找到。
回答by robjmills
EDIT just realised values from different arrays, could array_mergefirst but not sure thats what you want
编辑刚刚实现了来自不同数组的值,可以先使用array_merge但不确定那是你想要的
回答by Kzqai
I often use natsort(Natural Sort), since I usually just want to preserve the array for later use anyway.
我经常使用natsort(自然排序),因为我通常只想保留数组以备后用。
Example:
例子:
natsort($unsorted_array);
var_dump($usorted_array); // will now be sorted.

