fork(2) download
  1. <?php
  2.  
  3. function build_index($words)
  4. {
  5. $index = [];
  6. $current = null;
  7. foreach($words as $word) {
  8. $firstLetter = mb_strtolower(mb_substr($word, 0, 1, 'utf-8'), 'utf-8');
  9. echo $firstLetter;
  10. if (!$current || $current['letter'] !== $firstLetter) {
  11. $index[] = [
  12. 'letter' => $firstLetter,
  13. 'data' => []
  14. ];
  15. $current = &$index[count($index)-1];
  16. }
  17. $current['data'][] = $word;
  18. }
  19.  
  20. return $index;
  21. }
  22.  
  23.  
  24. // get data from DB
  25. $words = ['Привет', 'Медвед', 'Пиво'];
  26. sort($words);
  27. // build index
  28. $index = build_index($words);
  29. var_dump($index);
  30.  
  31. // render index
  32.  
  33.  
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
мппarray(2) {
  [0]=>
  array(2) {
    ["letter"]=>
    string(2) "м"
    ["data"]=>
    array(1) {
      [0]=>
      string(12) "Медвед"
    }
  }
  [1]=>
  array(2) {
    ["letter"]=>
    string(2) "п"
    ["data"]=>
    array(2) {
      [0]=>
      string(8) "Пиво"
      [1]=>
      string(12) "Привет"
    }
  }
}