Разбить массив на многомерный массив по алфавиту

У меня есть массив PHP, возвращенный мне в следующем формате:

[0] => Array
(
[mainCatID] => 2
[mainCatCode] => cat2
[mainCatDesc] => Acupuncture
[mainCatAddedDate] => 2016-10-12 10:22:49
[mainCatStatus] => active
)

[1] => Array
(
[mainCatID] => 3
[mainCatCode] => cat3
[mainCatDesc] => Medical
[mainCatAddedDate] => 2016-10-12 10:22:49
[mainCatStatus] => active
)

[2] => Array
(
[mainCatID] => 4
[mainCatCode] => cat4
[mainCatDesc] => Aids & Hiv
[mainCatAddedDate] => 2016-10-12 10:22:49
[mainCatStatus] => active
)[3] => Array
(
[mainCatID] => 1
[mainCatCode] => cat1
[mainCatDesc] => Brains
[mainCatAddedDate] => 2016-10-12 10:22:49
[mainCatStatus] => active
)

Чего я хотел бы добиться, так это разделить массив на различные алфавитные «куски» на основе первого алфавита [mainCatDesc]. Таким образом, ожидается, что результат будет следующим:

Accupunture
вспомогательные средства & ВИЧ

В

Мозги

M

медицинская

Спасибо за помощь в продвижении! Ура!

  • Отредактировано *

пока у меня есть только

$con = open_connection();
$allMainCatArray = getAllMainCat($con);
close_connection($con);

echo "<pre>";
print_r($allMainCatArray);
echo "</pre>";

0

Решение

Сделайте этот простой цикл:

$newArray = [];//create a new array
foreach($array as $item) {
$letter = $item['mainCatDesc'][0];//get the first letterif (!ctype_alpha($letter)) {//test if its letter
$newArray['#'][] = $item['mainCatDesc'];

} else if(count($newArray[$letter])) {//test if the letter is in the array
$newArray[$letter][] = $item['mainCatDesc'];//save the value
} else {
$newArray[$letter] = [$item['mainCatDesc']];
}
}
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector