按字母顺序排列的组数组结果 PHP

2021-12-26 00:00:00 group-by foreach php

我使用下面的代码来显示图像 &网站名称形成数据库.

I'm using below code to display Image & Name of webisites form database.

<fieldset>  
    <h1>A</h1>          
    <ul>
        <?php foreach ($records as $key) { ?>
        <li class="siteli"> <a href="#" class="add">        
            <div id="site-icon"><img src="<?php echo $key->site_img; ?>" width="16" height=""></div>
            <p id="text-site"> <?php echo $key->site_name; ?></p>
        </li>
        <?php } ?>
    </ul>
</fieldset>

现在我尝试通过添加 A、B、C 等作为标题,按字母顺序对这些结果进行分组.

Now I'm trying to group this results alphabetically by adding A, B, C etc as title.

示例,

A    
Amazon     
Aol    
Aol Mail

B    
Bing     
Bogger

推荐答案

您可以使用 array排序 对数组进行排序.在你的情况下,我会选择 sort()

You can use array sorting to sort the array. In your case I would choose sort()

现在显示带有我将使用的前一个字母的链接:

Now to show the links with a preceding Letter I would use:

<?php
$records = ['Aaaaa', 'Aaaa2', 'bbb', 'bbb2', 'Dddd'];
$lastChar = '';
sort($records, SORT_STRING | SORT_FLAG_CASE); //the flags are needed. Without the `Ddd` will come before `bbb`.
//Available from version 5.4. If you have an earlier version (4+) you can try natcasesort()

foreach($records as $val) {
  $char = $val[0]; //first char

  if ($char !== $lastChar) {
    if ($lastChar !== '')
      echo '<br>';

    echo strtoupper($char).'<br>'; //print A / B / C etc
    $lastChar = $char;
  }

 echo $val.'<br>';
}
?>

这将输出类似

A
Aaaa2
Aaaaa

B
bbb
bbb2

D
Dddd

请注意缺少 C,因为没有以 C 开头的单词.

Notice that the C is missing, because there are no words starting with C.

相关文章