How to display an Array under alphabetical letters using PHP?

后端 未结 6 1986
傲寒
傲寒 2021-02-04 17:06

I have an array that already contains all it\'s values in alphabetical order:

Alligator
Alpha
Bear
Bees
Banana
Cat
Cougar

Now I just want to li

6条回答
  •  遥遥无期
    2021-02-04 17:33

    here is another simple solution:-

    $result = array();
    foreach ($list as $item) {
        $firstLetter = substr($item, 0, 1);
        $result[$firstLetter][] = $item;
    }
    
    echo "
    "; print_r($result);
    

    Output :-

    Array (
    [A] => Array
        (
            [0] => Alligator
            [1] => Alpha
        )
    
    [B] => Array
        (
            [0] => Bear
            [1] => Bees
            [2] => Banana
        )
    
    [C] => Array
        (
            [0] => Cat
            [1] => Cougar
        )
     )
    

提交回复
热议问题