Hi, could something like this work for you ?
$sortedCities = $cities->groupBy(function($city,$id){
return Str::limit($city,1,'');
}, true)->unique();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi all.
I have a table of cities in the database.
I need to generate an array of the following form:
[
['A'] => [
18 => 'Alexandria',
24 => 'Antioch',
1679 => 'Akron',
1875 => 'Atlanta',
2713 => 'Abilene',
],
['B'] => [
28 => 'Bakersfield',
154 => 'Billings',
1495 => 'Bridgeport',
2150 => 'Baltimore',
4117 => 'Bend',
]
]
I tried to write the code myself, but it turned out to be big. I'm sure there is a more succinct solution.
$cities = City::pluck('title', 'id');
$letters = $cities->sort()->map(function($value) {
return Str::limit($value, 1, '');
})->unique()->flatten();
$lettersArray = [];
foreach ($letters as $letter) {
foreach($cities as $key => $city) {
if ($letter == Str::limit($city, 1, '')) {
$lettersArray[$letter][$key] = $city;
}
}
}
How can I refactor it?
And I also need to sort the cities by name within the array. I don't understand how to do it. sort() doesn't work.
Hi, could something like this work for you ?
$sortedCities = $cities->groupBy(function($city,$id){
return Str::limit($city,1,'');
}, true)->unique();
Please or to participate in this conversation.