santa
santa

Reputation: 12512

Sorting array by letter

Is it possible to output the results of an array into an HTML list sorted in alphabetical order. Here's what I mean. I have an array in the following format:

$myArray = array(
    "apple" => "Fruit that grows ...", 
    "car" => "Vehicle on four...", 
    "ant" => "Insect ..."
    ...
);

Desired output:

<ul>A
   <li>ant</li>
   <li>apple</li>
</ul>
<ul>C
   <li>car</li>
</ul>

etc.

Upvotes: 0

Views: 113

Answers (2)

TachyonVortex
TachyonVortex

Reputation: 8572

First, sort the array alphabetically by key:

ksort($myArray);

Or if you want to do a case-insensitive sort:

uksort($myArray, "strnatcasecmp");

Then create a temporary array to group all words starting with the same letter into sub-arrays:

$arrTemp = array();
foreach($myArray as $strKey => $strValue) {
    $strLetter = strtolower( substr($strKey, 0, 1) );
    if(array_key_exists($strLetter, $arrTemp) === FALSE) {
        $arrTemp[$strLetter] = array();
    }
    array_push( $arrTemp[$strLetter], $strKey );
}

Finally, render the HTML:

foreach($arrTemp as $strLetter => $arrWords) {
    print('<ul>' . strtoupper($strLetter));
    foreach($arrWords as $strWord) {
        print('    <li>' . $strWord . '</li>');
    }
    print('</ul>');
}

Upvotes: 2

Dan
Dan

Reputation: 2093

You can use the following to order the array alphabetically by the key:

ksort($myArray);

Upvotes: 2

Related Questions