<?php
function build_index($words)
{
$index = [];
$current = null;
foreach($words as $word) {
echo $firstLetter;
if (!$current || $current['letter'] !== $firstLetter) {
$index[] = [
'letter' => $firstLetter,
'data' => []
];
$current = &$index[count($index)-1]; }
$current['data'][] = $word;
}
return $index;
}
// get data from DB
$words = ['Привет', 'Медвед', 'Пиво'];
// build index
$index = build_index($words);
// render index
PD9waHAKCmZ1bmN0aW9uIGJ1aWxkX2luZGV4KCR3b3JkcykKewogICAgICAgICRpbmRleCA9IFtdOwogICAgICAgICRjdXJyZW50ID0gbnVsbDsKICAgICAgICBmb3JlYWNoKCR3b3JkcyBhcyAkd29yZCkgewogICAgICAgICAgICAgICAgJGZpcnN0TGV0dGVyID0gbWJfc3RydG9sb3dlcihtYl9zdWJzdHIoJHdvcmQsIDAsIDEsICd1dGYtOCcpLCAndXRmLTgnKTsKICAgICAgICAgICAgICAgIGVjaG8gJGZpcnN0TGV0dGVyOwogICAgICAgICAgICAgICAgaWYgKCEkY3VycmVudCB8fCAkY3VycmVudFsnbGV0dGVyJ10gIT09ICRmaXJzdExldHRlcikgewogICAgICAgICAgICAgICAgICAgICAgICAkaW5kZXhbXSA9IFsKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAnbGV0dGVyJyA9PiAkZmlyc3RMZXR0ZXIsCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJ2RhdGEnID0+IFtdCiAgICAgICAgICAgICAgICAgICAgICAgIF07CiAgICAgICAgICAgICAgICAgICAgICAgICRjdXJyZW50ID0gJiRpbmRleFtjb3VudCgkaW5kZXgpLTFdOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgJGN1cnJlbnRbJ2RhdGEnXVtdID0gJHdvcmQ7CiAgICAgICAgfQoKICAgICAgICByZXR1cm4gJGluZGV4Owp9CgoKLy8gZ2V0IGRhdGEgZnJvbSBEQgokd29yZHMgPSBbJ9Cf0YDQuNCy0LXRgicsICfQnNC10LTQstC10LQnLCAn0J/QuNCy0L4nXTsKc29ydCgkd29yZHMpOwovLyBidWlsZCBpbmRleAokaW5kZXggPSBidWlsZF9pbmRleCgkd29yZHMpOwp2YXJfZHVtcCgkaW5kZXgpOwoKLy8gcmVuZGVyIGluZGV4Cgo=