dongwei3866 2014-08-14 17:34
浏览 11
已采纳

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

I have this loop that sorts a set of results alphabetically and shows a <span> with the current letter, but I can't find a way to wrap each subset within a 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>';

}

I would like something like this

<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>

...

Right now what I get is

<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条回答 默认 最新

  • donglao4370 2014-08-14 17:42
    关注

    What about pre-grouping the brands before you loop through

    $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
    }
    

    And, ksort to make them alphabetical

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services