D
D
Dmitry Konyshev2015-01-08 18:38:31
PHP
Dmitry Konyshev, 2015-01-08 18:38:31

How to split an array of php links into blocks by the first letter of the link title?

There is an array like
rray
(
[0] => Array
(
[name] => Bryansk
)
[1] => Array
(
[name] => Voronezh
)
[2] => Array
(
[name] => Ekaterinburg
)
... [name] - these are links .
how can you make a division between cities for each letter in the output?
B
Bryansk
V
Voronezh
....

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2015-01-08
@Nc_Soft

<?php
$data = [
    [
        'name' => 'Брянск'
    ],
    [
        'name' => 'Москва'
    ],
    [
        'name' => 'Бобруйск'
    ],
];

usort($data, function ($v1, $v2) {
    return strcmp($v1['name'], $v2['name']);
});

$letter = null;
foreach ($data as $v) {
    $currentLetter = mb_substr($v['name'], 0, 1, 'utf-8');
    if ($currentLetter !== $letter) {
        $letter = $currentLetter;
        echo "--- $letter ---", PHP_EOL;
    }
    echo $v['name'], PHP_EOL;
}

--- B ---
Bobruisk
Bryansk
--- M ---
Moscow

A
Alexey Yakhnenko, 2015-01-08
@ayahnenko

It's not entirely clear what "[name] are links." means.
but generally something like that.

$cities = array(...);
$cities_with_letters = array();
foreach ($cities as $city) {
  $letter = substr($city['name'], 0, 1);
  $cities_with_letters[$letter][] = $city;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question