$data = [
['id' => '1', 'name' => 'яблоко'],
['id' => '2', 'name' => 'банан'],
['id' => '3', 'name' => 'баклажан'],
['id' => '4', 'name' => 'арбуз'],
['id' => '5', 'name' => 'апельсин'],
];
$data = [
[
['id' => '4', 'name' => 'арбуз'],
['id' => '5', 'name' => 'апельсин'],
],
[
['id' => '2', 'name' => 'банан'],
['id' => '3', 'name' => 'баклажан']
],
[
['id' => '1', 'name' => 'яблоко'],
]
];
<div class="letter_brand_block">
<div class="brand">
<div class="letter_block">
<a class="letter" href="#">A</a>
</div>
<a href="#" class="brand_name_block">Acura</a>
</div>
<div class="brand">
<a href="#" class="brand_name_block">Alfa Romeo</a>
</div>
<div class="brand">
<a href="#" class="brand_name_block">Alfa Romeo</a>
</div>
</div>
<div class="letter_brand_block">
<div class="brand">
<div class="letter_block">
<a class="letter" href="#">A</a>
</div>
<a href="#" class="brand_name_block">Acura</a>
</div>
<div class="brand">
<a href="#" class="brand_name_block">Alfa Romeo</a>
</div>
<div class="brand">
<a href="#" class="brand_name_block">Alfa Romeo</a>
</div>
<div class="brand">
<a href="#" class="brand_name_block">Alfa Romeo</a>
</div>
<div class="brand">
<a href="#" class="brand_name_block">Alfa Romeo</a>
</div>
</div>
function splitByFirstLetter(array $arr, $key="name")
{
$splitted = [];
foreach ($arr as $element) {
$firstLetter = mb_substr($element[$key], 0, 1);
$splitted[$firstLetter][] = $element;
}
return $splitted;
}
$data = [
['id' => '1', 'name' => 'яблоко'],
['id' => '2', 'name' => 'банан'],
['id' => '3', 'name' => 'баклажан'],
['id' => '4', 'name' => 'арбуз'],
['id' => '5', 'name' => 'апельсин'],
];
$data = splitByFirstLetter($data);
ksort($data); // сортировка свежеполученного массива по алфавиту.
/*
Output:
array(3) {
["а"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "4"
["name"]=>
string(10) "арбуз"
}
[1]=>
array(2) {
["id"]=>
string(1) "5"
["name"]=>
string(16) "апельсин"
}
}
["б"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "2"
["name"]=>
string(10) "банан"
}
[1]=>
array(2) {
["id"]=>
string(1) "3"
["name"]=>
string(16) "баклажан"
}
}
["я"]=>
array(1) {
[0]=>
array(2) {
["id"]=>
string(1) "1"
["name"]=>
string(12) "яблоко"
}
}
}
*/
SELECT * FROM table ORDER BY name ASC | DESC
$request = $pdo->prepare("SELECT `id`, `name` FROM `fruits` ORDER BY `name`");
$request->execute();
$data = [];
$prevLetter = '';
$subArray = [];
foreach ($row = $request->fetch(PDO::FETCH_ASSOC)) {
$firstLetter = mb_substr($row['name'], 0, 1);
if ($prevLetter != $firstLetter) {
if (count($subArray) > 0)
$data[] = $subArray;
$subArray = [];
$prevLetter = $firstLetter;
}
$subArray[] = $row;
}
if (count($subArray) > 0)
$data[] = $subArray;