Search code examples
phparraysmultidimensional-arraysplitalphabetical

Split na array to a multidimensional array alphabetically


I have a PHP array returned to me in the following format:

[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
    )

What I would like to achieve is to split the array into different alphabetical "chunks" based on the [mainCatDesc] first alphabet. So the result is expected to be like the following:

A

Accupunture Aids & Hiv

B

Brains

M

Medical

Thanks for the help in advance! Cheers!

  • Edited *

so far I only have

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

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

Solution

  • Do this simple loop:

    $newArray = [];//create a new array
    foreach($array as $item) {
       $letter = $item['mainCatDesc'][0];//get the first letter
    
    
       if (!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']];
       }
    }