本文介紹了按字母順序排列的組數組結果 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.
這篇關于按字母順序排列的組數組結果 PHP的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!