Разделение списка по первой букве
Чтобы разделить список элементов в PHP по первой букве, можно перебрать его и сгруппировать в новый ассоциативный массив, где ключами будут первые буквы, а значениями — массивы элементов, начинающихся с этой буквы.
Вот пример:
<?php
$items = [
"Apple",
"Banana",
"Cherry",
"Date",
"Apricot",
"Blueberry",
"Carrot",
"Dragonfruit"
];
$groupedItems = [];
foreach ($items as $item) {
$firstLetter = strtoupper(substr($item, 0, 1)); // Get the first letter and convert to uppercase
// If the first letter key doesn't exist in $groupedItems, create an empty array for it
if (!isset($groupedItems[$firstLetter])) {
$groupedItems[$firstLetter] = [];
}
// Add the current item to the array corresponding to its first letter
$groupedItems[$firstLetter][] = $item;
}
// Optional: Sort the grouped items by their first letter (key)
ksort($groupedItems);
// Output the grouped items for demonstration
foreach ($groupedItems as $letter => $itemsInGroup) {
echo "<h2>" . $letter . "</h2>";
echo "<ul>";
foreach ($itemsInGroup as $item) {
echo "<li>" . $item . "</li>";
}
echo "</ul>";
} ?>
Для кириллицы substr() заменяем на mb_substr(). Это нужно для работы со строками, поддерживающие многобайтные кодировки. В юникоде русские буквы - 2 байта, латинские и пробел - 1 байт.