Jump to content

Directory listing with first letter displayed


Ty44ler

Recommended Posts

I'm trying to get a listing of my directory that shows the first letter and then all the names that start with that letter. Here is my code:

for($i = 65; $i < 91; $i++) {
	foreach (glob("{".chr($i).",".chr($i+32)."}*", GLOB_BRACE|GLOB_ONLYDIR) as $directoryname) {
		echo chr($i)."| ".$directoryname; 
}
}

 

But here's my output:

P | Project Red

P | Projects

P | Pants

R | Resumes

W | Warehouse Files

W | warrior

 

I want it to be like:

P | Project Red

    Projects

    Pants

R | Resumes

W | Warehouse Files

      Warrior

 

I know I have to move the chr($i) since it loops, but I'm not sure where to go from there.

Link to comment
Share on other sites

you will need to keep track of the last character you output, and if the current character to be output is the same, then you dont output it. Something like

 

//var will keep track of the last value of chr($i)
$lastVal = "";//set it to an empty string at the beginning

for($i = 65; $i < 91; $i++) {
	foreach (glob("{".chr($i).",".chr($i+32)."}*", GLOB_BRACE|GLOB_ONLYDIR) as $directoryname) {
                        //here we have a condition that decides if we output the chr($i) | part
                        echo ($lastVal != chr($i)) ? chr($i)."| " : "   "; //3 spaces so it looks even
		echo $directoryname; 
                        //now we update our lastVal variable to the current on generated
                        $lastVal = chr($i);
}
}

 

 

hope this helps

Link to comment
Share on other sites

EDIT: Looks like mikesta beat me to it, but this is nearly the same thing anyhow.

 

This seems to work as you describe. Just check what the last output was, and only output the letter if it changes, or is empty (indicating that it was the first iteration).

 

for($i = 65; $i < 91; $i++) {
      foreach (glob("{".chr($i).",".chr($i+32)."}*", GLOB_BRACE|GLOB_ONLYDIR) as $directoryname) {
         echo (empty($prev) || chr($i) != $prev) ? chr($i)." | $directoryname<br>" : "    $directoryname<br>";
         $prev = chr($i);
   }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.