PHP正确地使用数字输入字符串

时间:2014-09-04 02:46:51

标签: php string object usort

我想通过其中一个元素来使用一个对象,但我不确定如何对包含数字的字符串进行字符串比较,并且数字的位置并不总是相同。

例如在我的例子中,我想要排序的值如下所示: String (A), String (B), String bit longer 1, String bit longer 2, String bit longer 3, String bit longer 10, String bit longer 20(但不是按此顺序)

如果我做一个简单的strcmp()比较usort将它像mysql一样排序,所以顺序看起来像这样:String (A), String (B), String bit longer 1, String bit longer 10, String bit longer 2, String bit longer 20, String bit longer 3这是错误的

现在我被困住了,不应该做什么来正确排序。

编辑:

我正在尝试排序的对象看起来像这样:

Array
(
    [0] => stdClass Object
        ( [field] => String (A) ... lots of other fields )
    [1] => stdClass Object
        ( [field] => String (B) ... lots of other fields )
    [2] => stdClass Object
        ( [field] => String bit longer 1 ... lots of other fields )
    [3] => stdClass Object
        ( [field] => String bit longer 2 ... lots of other fields )
    ...and so on
)

1 个答案:

答案 0 :(得分:0)

对于字符串数组的排序,您可以使用natsort

php > print_r($ary);
Array
(
    [0] => String (A)
    [1] => String (B)
    [2] => String bit longer 1
    [3] => String bit longer 10
    [4] => String bit longer 2
    [5] => String bit longer 20
    [6] => String bit longer 3
)
php > natsort($ary);
php > print_r($ary);
Array
(
    [0] => String (A)
    [1] => String (B)
    [2] => String bit longer 1
    [4] => String bit longer 2
    [6] => String bit longer 3
    [3] => String bit longer 10
    [5] => String bit longer 20
)

对于较大对象的属性,请在传递给natsort的自定义比较函数中使用strnatcmpusort使用的比较函数:

function natcmpfield($obj1, $obj2) {
   return strnatcmp($obj1->fieldName, $obj2->fieldName);
}

usort($objArray, natcmpfield);

例如:

php > print_r($objArray);
Array
(
    [0] => Example Object ( [str] => String (A))
    [1] => Example Object ( [str] => String (B))
    [2] => Example Object ( [str] => String bit longer 1)
    [3] => Example Object ( [str] => String bit longer 10)
    [4] => Example Object ( [str] => String bit longer 2)
    [5] => Example Object ( [str] => String bit longer 20)
    [6] => Example Object ( [str] => String bit longer 3)
)
php > function natcmpfield($obj1, $obj2) {
    { return strnatcmp($obj1->str, $obj2->str);
    { }
php > usort($objArray, natcmpfield);
php > print_r($objArray);
Array
(
    [0] => Example Object ( [str] => String (A))
    [1] => Example Object ( [str] => String (B))
    [2] => Example Object ( [str] => String bit longer 1)
    [3] => Example Object ( [str] => String bit longer 2)
    [4] => Example Object ( [str] => String bit longer 3)
    [5] => Example Object ( [str] => String bit longer 10)
    [6] => Example Object ( [str] => String bit longer 20)
)