M
M
microf2019-03-21 17:16:34
Yii
microf, 2019-03-21 17:16:34

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]);
    }

and output
<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>

Everything is displayed perfectly
. But they reminded me that these are not just names, but links with urls. Accordingly, the array will be different
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" }

those. consisting of other arrays. I can sort it, of course, but how can I display it so that there is a letter?
A
Alex
Do I need to write it down somewhere? create a two-dimensional array element between other elements? What have I missed

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Bay, 2019-03-21
@kawabanga

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 question

Ask a Question

731 491 924 answers to any question