0

I have a list of folders but want to group them by first letter ie all A folders together, all B folder together etc:

$handle = opendir(".");
$projectContents = '';
while ($file = readdir($handle)) 
{
    if (is_dir($file) && !in_array($file,$projectsListIgnore)) 
    {

$projectContents .= '<li><a href="'.$file.'">'.$file.'</a></li>';

    }
}
closedir($handle);

Output:

<ul>
 $projectContents
</ul>

The above snippet lists them fine from a-2-z but I don't know how to section them off into groups.

The closing and re-opening of </ul><ul> with each new letter section would be enough but again don't kow how to impliment into the current snippet.

Anna Riekic
  • 728
  • 1
  • 13
  • 30

2 Answers2

1

Compare the first character of the current file name in the loop with the first character of the previous one, then print the </ul><ul> if they're not the same:

$handle = opendir(".");
$projectContents = '';
$firstLetter = '';
while ($file = readdir($handle)) 
{
    if (is_dir($file) && !in_array($file,$projectsListIgnore)) 
    {
        if ($firstLetter != strtoupper($file{0}) && $firstLetter != '')
        {
            $projectContents .= '</ul><ul>';
        }
        $firstLetter = strtoupper($file{0}); // Store the current character for comparison
        $projectContents .= '<li><a href="'.$file.'">'.$file.'</a></li>';

    }
}
closedir($handle);
Plenka
  • 1,099
  • 7
  • 17
  • This sadly doesn't seem to work.#, not sure if you meant to use `{0}` or `[0]` but tried with both. – Anna Riekic Apr 13 '14 at 18:15
  • Update:should be `[0]` andI got it working by removing `&& $firstLetter != ''` (kind of). – Anna Riekic Apr 13 '14 at 18:22
  • It takes into account uppercase and lowercase and seperates them, anyway to combat this? – Anna Riekic Apr 13 '14 at 18:30
  • 1
    Both should work, as described on http://php.net/language.types.string.php#language.types.string.substr. I prefer the curly braces, as they make absolutely clear that the variable is not an array. `&& $firstLetter != ''` should not be removed, as it makes sure the `
      ` is not added on the first loop, but I made an error in placing `$firstLetter = $file{0};` in the if-statement. I'll update my answer, also for case insensitive comparisons.
    – Plenka Apr 13 '14 at 18:31
  • Thank you very much, I didn't know you could use curly braces too. – Anna Riekic Apr 13 '14 at 18:39
0

I would first store all the directories names in an array and than use asort() function to sort all the items alphabetically, and than do the link creation.

PlaviZG
  • 79
  • 1
  • 7