2017-02-11 87 views
0

我有以下代碼根據起始字符將字符串分成組。我現在試圖將所有數字合併到一個組中,而不是每個起始號碼都獲得自己的組。有人可以幫忙,因爲我不知道如何修改,以實現這一目標?輸入如何將數字合併爲一組

$last = ''; 
foreach($brandsArray as $words){ 
    $current = substr($words, 0, 1); 
    if(strtoupper($current) != strtoupper($last)) { 
     echo "\n 
     <a name=\"". strtoupper($current) ."\"><li class=\"title\">" . strtoupper($current) . "</li></a>\n\n"; 
    } 
    echo '<li>'. $words . "</li>\n"; 
    $last = $current; 
} 

例子:

1 
121 
57 
876 
Apple 
Apple1 
Banana 
Banana123 
Delta 

我想輸出看起來像

**#** 
1 
121 
57 
876 

**A** 
Apple 
Apple1 

**B** 
Banana 
Banana123 

**D** 
Delta 

什麼什麼公司目前做的是以下

**1** 
1 
121 

**5** 
57 

**8** 
876 

**A** 
Apple 
Apple1 

**B** 
Banana 
Banana123 

**D** 
Delta 
+0

請您提供輸入的樣本例子和預期產出 –

+0

'

  • " . strtoupper($words) . "
  • \ n \ n「; ' –

    +0

    @VeshrajJoshi - 更新以顯示輸入,它是什麼做的,我想什麼做 – KDJ

    回答

    1

    對於給定的輸入和預期的輸出上面提到。

    $brandsArray = array('1', '121', '57', '876', 'Apple', 'Apple1', 'Banana', 'Banana123', 'Delta'); 
    $last = ''; 
    foreach($brandsArray as $words){ 
        // setting the current value as # if is number 
        $current = is_numeric($words)?"#":substr($words, 0, 1); 
        if (strtoupper($current) != strtoupper($last)) { 
         echo "\n 
         <a name=\"". strtoupper($current) ."\"><li class=\"title\">" . strtoupper($current) . "</li></a>\n\n"; 
        } 
        echo '<li>'. $words . "</li>\n"; 
        $last = $current; 
    } 
    
    相關問題