2014-09-04 35 views
0

我想通過它的一個元素來使用對象,但我不知道如何對包含數字的字符串進行字符串比較,並且數字的位置並不總是相同。PHP使用正確數字的字符串

例如在我的情況的值,我想排序是這樣的: 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 
) 
+0

你想要做一個自然排序? – Barmar 2014-09-04 02:50:49

+1

你看過'natsort()'嗎? – Barmar 2014-09-04 02:51:32

+0

那麼正確的排序是什麼? – Ghost 2014-09-04 02:55:34

回答

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,strnatcmp所使用的比較函數,在您傳遞給的自定義比較函數中:

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) 
) 
+0

謝謝你現在正確的工作。我不知道發生了什麼,但首先它完全分類像1,2,10,20,3,4,22,23,比重新上傳編輯後的文件像魅力一樣。 – 2014-09-04 03:32:22