Php 按字母顺序排列的标题列表

Php 按字母顺序排列的标题列表,php,list,alphabetical,heading,Php,List,Alphabetical,Heading,如何用字母标题扩展列表。 例如: A 锚 畜生 B 公共汽车 烧 E 吃 欧元 这是我的代码: <ol class="items brand-items"> <?php foreach ($block->getBrands() as $brand): ?> <li class="item brand-item"> <?php echo $block->escape

如何用字母标题扩展列表。 例如:

A 锚 畜生

B 公共汽车 烧

E 吃 欧元

这是我的代码:

    <ol class="items brand-items">
        <?php foreach ($block->getBrands() as $brand): ?>
            <li class="item brand-item">
                <?php echo $block->escapeHtml($brand->getName()) ?>
            </li>
        <?php endforeach; ?>
    </ol>

假设您的输入为:

$list = ['apple', 'and', 'another', 'ball', 'bat', 'cat', 'call'];
您希望的输出是:

Array (
    [a] => Array
        (
            [0] => apple
            [1] => and
            [2] => another
        )

    [b] => Array
        (
            [0] => ball
            [1] => bat
        )

    [c] => Array
        (
            [0] => cat
            [1] => call
        )

)
你应该这样做:

$out = [];

foreach ($list as $brand) {
  $out[substr($brand,0,1)][] = $brand;

}

打印美元

请说得更具体些。你的问题不清楚。我已经用我的实际代码更新了问题。你想按第一个字符对品牌名称进行分组吗?是的,我想按第一个字符对品牌名称进行分组。