本文介绍了按字母顺序排列PHP组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用下面的代码来显示图片&
< 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 =16height =>< / div>
< p id =text-site> <?php echo $ key-> site_name; ?>< / p为H.
< / li>
<?php}?>
< / ul>
< / fieldset>
现在我试图按照字母顺序将A,B,C等作为标题进行分组。
例子,
A
Amazon
Aol
Aol Mail
B
Bing
Bogger
解决方案
您可以使用排序数组。在你的情况下,我会选择
现在使用前面的信件显示链接:
<?php
$ records = ['aaaaa','aaaa2','bbb','bbb2','Dddd'];
$ lastChar ='';
sort($ records,SORT_STRING | SORT_FLAG_CASE); //标志是需要的。没有`Ddd`就会在`bbb`之前。
//可从版本5.4获得。如果你有一个更早的版本(4 +),你可以尝试natcasesort()
foreach($记录为$ val){
$ char = $ val [0]; ($ char
$ b $ if($ char!== $ lastChar){
if($ lastChar!=='')
echo'< br>';
echo strtoupper($ char)。'< br>'; //打印A / B / C等
$ lastChar = $ char;
}
echo $ val。'< br>';
}
?>
这会输出类似于
<$ p $ a
aaaa2
aaaaa
b
bbb
bbb2
D
dddd
请注意,C缺失,因为没有以C开头的单词。
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>
Now I'm trying to group this results alphabetically by adding A, B, C etc as title.
Example,
A
Amazon
Aol
Aol Mail
B
Bing
Bogger
解决方案
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>';
}
?>
This will output something like
A
Aaaa2
Aaaaa
B
bbb
bbb2
D
Dddd
Notice that the C is missing, because there are no words starting with C.
这篇关于按字母顺序排列PHP组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!