Alphabetical Order

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Alphabetical Order

Post by Mr Tech »

This is my code that displays files from a directory:

Code: Select all

<?php
$handle=opendir($root.$folder);
while ($file2 = readdir($handle)) {
	if (is_file($root.$folder."/$file2")) {

$content = fileread($root.$folder.$file2);
if( preg_match( "/<title>([^<]*)<\/title>/is", $content, $match ) )
$title = $match[1];
if ($title == "") {
if( preg_match( "/title = \"([^\"]*)\";/is", $content, $match ) )
$title = $match[1];
}
if ($title == "") {
$title = "No Title";
}
?>
<tr>
<td><a href="..<?php echo $folder.$file2; ?>" target="_blank"><?php echo $file2; ?></a></td>
<td><?php echo $title; ?></td>
<td><?php echo $size; ?> bytes</td>
</tr>
<?php
}
}
closedir($handle); 
?>
Basically what I want it tro do is show the files in alphabetical order. How would I do this?
Last edited by Mr Tech on Wed Feb 01, 2006 6:00 pm, edited 1 time in total.
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Post by Mr Tech »

BTW, it needs to order by the $file2 wording...
Roja
Tutorials Group
Posts: 2692
Joined: Sun Jan 04, 2004 10:30 pm

Post by Roja »

User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Post by Mr Tech »

Thanks Roja.

The thing is, this is the code that is sorted:

Code: Select all

<tr>
<td><a href="..<?php echo $folder.$file2; ?>" target="_blank"><?php echo $file2; ?></a></td>
<td><?php echo $title; ?></td>
<td><?php echo $size; ?> bytes</td>
</tr>

Code: Select all

How will it sort that when it has all the HTML coding in the way? Any ideas?
RobertPaul
Forum Contributor
Posts: 122
Joined: Sun Sep 18, 2005 8:54 pm
Location: OCNY

Post by RobertPaul »

Take the HTML out of the while loop. Grab all the file data you need and dump it in an array. Something like:

Code: Select all

Array
(
    [0] => Array
        (
            [file] => some_file_name.ext
            [title] => Some Title
            [size] => 12901
        )
    [1] => Array
        (
            [file] => some_other_file.ext
            [title] => Another Title
            [size] => 45915
        )
)
Then you can sort it with usort() and output your HTML by iterating over the array, which will be in alphabetical order based on title. ;)
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Post by Mr Tech »

Thanks RobertPaul,

I don't mean to be such a noob but can you give an example of how to "dump it all into the array"? I'm not sure how to put all the information togetehr so that the filename gets the right tiel and file size.....

Cheers ;)
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

http://www.php.net/glob this will put it into an array for you
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Post by Mr Tech »

I'm getting a glob function does not exist error. Any other ways?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

you may want to look at natsort() while looking at sort().
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

You must be on PHP 4 < 4.3.0


Here is the glob function you need

Code: Select all

if(!(function_exists('glob')))
{function glob($pattern)
 {#get pathname (everything up until the last / or \)
  $path=$output=null;
  if(PHP_OS=='WIN32')
   $slash='\\';
  else
   $slash='/';
  $lastpos=strrpos($pattern,$slash);
  if(!($lastpos===false))
  {$path=substr($pattern,0,-$lastpos-1); #negative length means take from the right
   $pattern=substr($pattern,$lastpos);
  }
  else
  {#no dir info, use current dir
   $path=getcwd();
  }
  $handle=@ opendir($path);
  if($handle===false)
   return false;
  while($dir=readdir($handle))
  {if(pattern_match($pattern,$dir))
   $output[]=$dir;
  }
  closedir($handle);
  if(is_array($output))
   return $output;
  return false;
 }

 function pattern_match($pattern,$string)
 {#basically prepare a regular expression
  $out=null;
  $chunks=explode(';',$pattern);
  foreach($chunks as $pattern)
  {$escape=array('$','^','.','{','}',
                 '(',')','[',']','|');
   while(strpos($pattern,'**')!==false)
   $pattern=str_replace('**','*',$pattern);
   foreach($escape as $probe)
   $pattern=str_replace($probe,"\\$probe",$pattern);
   $pattern=str_replace('?*','*',
             str_replace('*?','*',
             str_replace('*',".*",
               str_replace('?','.{1,1}',$pattern))));
   $out[]=$pattern;
  }
  if(count($out)==1)
   return(eregi("^$out[0]$",$string));
  else
   foreach($out as $tester)
   if(eregi("^$tester$",$string))
     return true;
   return false;
 }
}

Either this or build the array yourself then use sort()
RobertPaul
Forum Contributor
Posts: 122
Joined: Sun Sep 18, 2005 8:54 pm
Location: OCNY

Post by RobertPaul »

Here's what I was talking about ... not sure what all that glob business is.

This is only how I would do it, given your original code ... I wouldn't claim it's necessarily the best way.

Code: Select all

<?php 
$files = array();
$currentFile = array();
$dh = opendir($root.$folder);

while(FALSE !== ($file = readdir($dh)) {

	if(is_file($root.$folder.'/'.$file)) {
		$content = file_get_contents($root.$folder.'/'.file);
		
		if( preg_match( "/<title>([^<]*)<\/title>/is", $content, $match ) )
			$title = $match[1];

		if ($title == "") {
			if( preg_match( "/title = \"([^\"]*)\";/is", $content, $match ) )
				$title = $match[1];
		}

		if ($title == "") {
			$title = "No Title";
		} 
		
		$currentFile['title'] = $title;
		$currentFile['name'] = $file;
		$currentFile['size'] = filesize($root.$folder.'/'$file);
		
		$files[] = $currentFile;
	}
}

//now that all the file data is gathered sort it
usort($files, 'sortFiles');

foreach($files as $a) { ?>
	<tr>
		<td><a href="..<?php echo $folder.$a['name']; ?> target="_blank"><?php echo $a['name']; ?></a></td>
		<td><?php echo $a['title'] ?></td>
		<td><?php echo $a['size'] ?></td>
	</tr>
	<?php }
	
function sortFiles($a, $b) {
	return strcasecmp($a['name'], $b['name']);
}
?>
Post Reply