2013-05-31 15 views
1

我現在有一個顯示像這樣的數據代碼:有序列表組數字,符號

1 
11 Title Here 

2 
21 Guns 

A 
Awesome 

使用此:

foreach($animes as $currentAnime){ 
     $thisLetter = strtoupper($currentAnime->title[0]); 
     $sorted[$thisLetter][] = array('title' => $currentAnime->title, 'id' => $currentAnime->id); 
     unset($thisLetter); 
    } 

我怎麼組中的所有號碼爲#,所有的符號a ~

像這樣:

# 
11 Title Here 
21 Guns 

~ 
.ahaha 

A 
Awesome 

謝謝你的建議。

+0

如果這是一個數字和preg_match(如果這是一個符號並向數組添加另一個維度),則可以使用is_numeric()進行檢查。 – Robert

回答

0

如果這是一個數字,你可以用is_numeric()查詢,如果這是一個符號,可以用preg_match()查詢。

foreach($animes as $currentAnime){ 
    $thisLetter = strtoupper($currentAnime->title[0]); 
    if(is_numeric($thisLetter)) 
    { 
    $sorted['#'][] = array('title' => $currentAnime->title, 'id' => $currentAnime->id); 
    } 
    else if(preg_match('/[^a-zA-Z0-9]+/', $thisLetter)) 
    { 
      $sorted['~'][] = array('title' => $currentAnime->title, 'id' => $currentAnime->id); 
    } 
    else 
    { 
      $sorted[$thisLetter][] = array('title' => $currentAnime->title, 'id' => $currentAnime->id); 
    } 
    unset($thisLetter); 
} 

[^a-zA-Z0-9]+ - 適合信,如果沒有AZ字母也沒有AZ字符也不0-9數字中可加入,將不適合和你沒有精確的千篇一律,所以我已經添加了哪些字符的字符正則表達式的基礎。此外,您還可以檢查是否只有[a-zA-Z]+有一個字母,並將其添加到字符串組,並且最後的「else」語句將用於非數字字符串的字符串。