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.

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

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);
   }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.