Answer the question
In order to leave comments, you need to log in
How to display an array in alphabetical order with a heading letter?
Good afternoon. I'm confused. I had to display the list from the array:
A
Andrey
Alexander
B
Boris
Balda
everything is ok with him
$model = ["alex", "gina", "gena", "reva","psih","ter","denis"];
$result = array();
{
parent::init();
sort($this->model);
}
public function run()
{
$result = array();
$previous = null;
$i = 0;
foreach ($this->model as $value) {
$firstLetter = substr($value, 0, 1);
if ($previous !== $firstLetter) {
$result[$i] = mb_convert_case($firstLetter, MB_CASE_UPPER, "UTF-8");
$i++; //тут просто для ясности
}
$result[$i] = $value;
$previous = $firstLetter;
$i++;
}
return $this->render('index', ['result' => $result]);
}
<ul>
<?php
foreach ($result as $res) {
if (iconv_strlen($res) == 1) {
?> <li class="list__item--one">
<?php echo $res; ?></li>
<?php
} else {
?>
<li class="list__item"><a href="">
<?php echo $res ?></a> </li> <?php
}
}
?>
</ul>
array(6) { [0]=> array(3) { ["id"]=> string(1) "1" ["name"]=> string(4) "Alex" ["url_name"]=> string(8) "url_Alex" } [3]=> array(3) { ["id"]=> string(1) "6" ["name"]=> string(5) "Denis" ["url_name"]=> string(9) "url_denis" } [1]=> array(3) { ["id"]=> string(1) "2" ["name"]=> string(4) "Gast" ["url_name"]=> string(8) "url_gast" } [2]=> array(3) { ["id"]=> string(1) "5" ["name"]=> string(4) "Gina" ["url_name"]=> string(8) "url_gina" } [4]=> array(3) { ["id"]=> string(1) "9" ["name"]=> string(8) "Ortopedy" ["url_name"]=> string(12) "url_ortopedy" } [5]=> array(3) { ["id"]=> string(2) "10" ["name"]=> string(4) "Torn" ["url_name"]=> string(9) "url_thorn" }
Answer the question
In order to leave comments, you need to log in
stage 1 - multisort by name field.
step 2 - foreach pass, write the current capital letter to the variable.
$letter = '';
forearch ($result as $res) {
if ({первая буква имени <> $letter}) { $letter = {первая буква}; echo $letter; }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question