PHP:在div中以相同的字母开头包装每组单词

时间:2014-08-14 17:34:33

标签: php loops

我有这个循环按字母顺序对一组结果进行排序,并显示带有当前字母的<span>,但我找不到将每个子集包装在div中的方法。

<?php

$previousLetter = null;

foreach($allBrands as $brand) {


    $firstLetter = strtolower($brand->name[0]);

    if ( $previousLetter != $firstLetter ) {

        echo '<span class="designer-first-letter">'. $firstLetter .'</span>';

        $previousLetter = $firstLetter;


    }

    echo '<p>'.$brand->name.'</p>';

}

我想要这样的东西

<div>
    <span>A</span>
    <p>Aword</p>
    <p>Aword2</p>
    <p>Aword3</p>
    <p>...</p>
</div>

<div>
    <span>B</span>
    <p>Bword</p>
    <p>Bword2</p>
    <p>Bword3</p>
    <p>...</p>
</div>

<div>
    <span>C</span>
    <p>Cword</p>
    <p>Cword2</p>
    <p>Cword3</p>
    <p>...</p>
</div>

...

现在我得到的是

<span>A</span>
<p>Aword</p>
<p>Aword2</p>
<p>Aword3</p>
<p>...</p>

<span>B</span>
<p>Bword</p>
<p>Bword2</p>
<p>Bword3</p>
<p>...</p>

<span>C</span>
<p>Cword</p>
<p>Cword2</p>
<p>Cword3</p>
<p>...</p>

...

1 个答案:

答案 0 :(得分:2)

如何在循环之前预先对品牌进行分组

$brands = Array("Aword", "Aword2", "Aword3", "BWord", "Bword2");
$groups = Array();

foreach($brands as $brand) { 
    $startsWith = strtolower($brand[0]);

    if( array_key_exists($startsWith, $groups))
        array_push($groups[$startsWith], $brand);
    else 
    {
        $groups[$startsWith] = Array($brand);
    }
}

ksort($groups);

foreach($groups as $key => $value ) {
    ?>
    <div>
        <span><?php echo strtoupper($key) ?></span>
        <?php foreach($value as $brand) { ?>
        <p><?php echo $brand?></p>
        <?php } ?>
    </div>
    <?php
}

并且,ksort使它们按字母顺序排列