Jump to content

Sort By Type


Recommended Posts

ok i currently have a code that displays all the files in the directory as well as their file size (bytes)
here it is:

[b]get file name:[/b][code]<?php
//read the directory (get file name)
if ($handle = opendir('.')) {
  while (false !== ($file = readdir($handle))) {
//check hide these files:
      if ($file != "." && $file != ".." && $file != "index.php" && $file != "upload.php" && $file != "index.html" && !is_dir($file)) {
//display file name:
          echo "<a href='" . $file . "'>" . $file . "</a><br/>";
      }
  }
  closedir($handle);
}
?>[/code]

[b]Get file size:[/b][code]<?php
//read directory (get file size)
if ($handle = opendir('.')) {
  while (false !== ($file = readdir($handle))) {
//again, hide these files:
      if ($file != "." && $file != ".." && $file != "index.php" && $file != "upload.php" && $file != "index.html" && !is_dir($file)) {
//display file size, divided by 1000 to get it in KB's ;)
          echo (filesize($file)/1000) . ' KB' . "<br/>";
      }
  }
  closedir($handle);
}
?>[/code]

now i want to make it so that you can sort by file size, file name, and/or date uploaded
can someone please get me started with this?
i never really got how you did the [i]index.php?sort=size[/i] thing, and so if your using that method, please try to explain it.
Link to comment
Share on other sites

I can give you an overview of how I would do it..

First I would put all the relevant data into an 2-level array, like this:

$files[] = array(
  'name' => $filename,
  'size' => $filesize($filename),
);

Then I would sort it using a user sort function, like this:

usort(&$files, 'filesize_cmp');

function filesize_cmp($a, $b) {
  if ($a['size'] < $b['size']) return -1;
  if ($a['size'] > $b['size']) return 1;
  return 0;
}

Take a look at the documentation page for usort() to get an idea of what it's about.  It's a very flexible function.
Link to comment
Share on other sites

There´s no need for a callback-function to sort in this case. Just make sure the filesize goes into the first index of the multidimensionall array, like this:

[code]$array[] = array(
'size' => filesize($file),
'name' => $file
);[/code]


and then run the array thru [url=http://www.php.net/array_multisort]array_multisort()[/url]


Example: loads all files from the current directory and sort by filesize (ascending), if you´d like to sort it in reversed order, use [url=http://www.php.net/array_reverse]array_reverse()[/url] after the [url=http://www.php.net/array_multisort]array_multisort()[/url] function.

[hr]
[code=php:0]<?php

foreach(glob("*.*") as $file) {

if ($file != "index.php" && $file != "upload.php" && $file != "index.html")
$array[] = array('size' => filesize($file), 'name' => $file);

}

array_multisort($array);
print_r($array);

?>[/code]
[hr]

If you only want to fetch a specific filetype from your dir, all jpg´s for example, then remove the if-case and change the for-case to this:

[code=php:0]foreach(glob("*.jpg") as $file)[/code]


if you´d like to get more than 1 filetype, then you can add more extensions by doing like this:

[code=php:0]foreach(glob("*.{jpg,png,gif}", GLOB_BRACE) as $file)[/code]
Link to comment
Share on other sites

Oops  ;) then do something like this, add a switch-case to determine how the array should be sorted


ex
[hr]
[code=php:0]<?php

foreach(glob("*.*") as $file) {

if ($file != "index.php" && $file != "upload.php" && $file != "index.html")

$size = filesize($file);
$date = date("Y-m-d H:i:s", filectime($file));

if (isset($_GET['sort'])) {

switch ($_GET['sort']) {

case 'size' : // Sort by size
$array[] = array('size' => $size, 'date' => $date, 'name' => $file);
break;

case 'date' : // Sort by date
$array[] = array('date' => $date, 'size' => $size, 'name' => $file);
break;

default : // Sort by name as  default
$array[] = array('name' => $file, 'size' => $size, 'date' => $date);

}

} else {

// If $_GET['sort'] isn´t set, sort by filename as default
$array[] = array('name' => $file, 'size' => $size, 'date' => $date);

}

}

array_multisort($array);
print_r($array);

?>[/code]
[hr]

If you´d like to sort by size - [color=blue]?sort=size[/color]
If you´d like to sort by date - [color=blue]?sort=date[/color]

If nothing or anything else is specified, the code will sort by filename as default
Link to comment
Share on other sites

[quote author=Nicklas link=topic=114453.msg466457#msg466457 date=1163252637]
Oops  ;) then do something like this, add a switch-case to determine how the array should be sorted


ex
[hr]
[code=php:0]<?php

foreach(glob("*.*") as $file) {

if ($file != "index.php" && $file != "upload.php" && $file != "index.html")

$size = filesize($file);
$date = date("Y-m-d H:i:s", filectime($file));

if (isset($_GET['sort'])) {

switch ($_GET['sort']) {

case 'size' : // Sort by size
$array[] = array('size' => $size, 'date' => $date, 'name' => $file);
break;

case 'date' : // Sort by date
$array[] = array('date' => $date, 'size' => $size, 'name' => $file);
break;

default : // Sort by name as  default
$array[] = array('name' => $file, 'size' => $size, 'date' => $date);

}

} else {

// If $_GET['sort'] isn´t set, sort by filename as default
$array[] = array('name' => $file, 'size' => $size, 'date' => $date);

}

}

array_multisort($array);
print_r($array);

?>[/code]
[hr]

If you´d like to sort by size - [color=blue]?sort=size[/color]
If you´d like to sort by date - [color=blue]?sort=date[/color]

If nothing or anything else is specified, the code will sort by filename as default
[/quote]

glob returns the full path so you need to change your test logic...

[code]if ($file != "index.php" && $file != "upload.php" && $file != "index.html")[/code]

Also it would be better to remove all those if(?) and switch() out of the loop, so you sort by, not loop and then question, question!


printf
Link to comment
Share on other sites

[quote]glob returns the full path so you need to change your test logic...[/quote]

Did you even try the code ::)

[quote]Also it would be better to remove all those if(?) and switch() out of the loop, so you sort by, not loop and then question, question![/quote]

"so you sort by" ? To be able to sort by filesize, date or filename  via variable, the array needs to built up in the right order and [u]then[/u] be sorted correctly with array_multisort().

If you happen to have a better suggestion, please share it with us and help [b]JustinMs66[/b]
Link to comment
Share on other sites

All I was trying to say is do your question outside the loop. I also I understand what your doing by glob ('*.*'), but if you work outside the directory you would need to include basename() to $file! As for the loop, your asking the same question over and over, which doesn't make a lot sense when you could do that logic out of the loop and only include ASC or DESC condition in the custom sorting function or in your array_multisort().

[code]
<?php

// the sorting function (str, int) based on $sort type

function sort_array ( $new, $old )
{
global $sort, $up, $dn;

if ( $sort == 0 )
{
if ( $dn == 1 )
{
return strcmp ( $new[$sort], $old[$sort] );
}

return strcmp ( $old[$sort], $new[$sort] );
}

if ( $new[$sort] == $old[$sort] )
{
return 0;
}
else if ( $new[$sort] < $old[$sort] )
{
return $up;
}

return $dn;
}

// files not to list

$bad = array ( 'index.php', 'upload.php', 'index.html' );

// default sort (file name) [0 = file name, 1 = file time, 2 = file size]

$sort = 0;

// default type (ASC) [0 = ASC, 1 = DESC]

$type = 0;

// test the sort

if ( isset ( $_GET['sort'] ) )
{
$temp = intval ( $_GET['sort'] );

if ( $temp >= 0 && $temp <= 2 )
{
$sort = $temp;
}
}

// test the type

if ( isset ( $_GET['type'] ) )
{
$temp = intval ( $_GET['type'] );

if ( $temp >= 0 && $temp <= 1 )
{
$type = $temp;
}
}

// set the condition for asc / desc

if ( $type == 0 )
{
$up = -1;
$dn  = 1;
}
else
{
$up  = 1;
$dn = -1;
}

// path to the directory to read

$path = './junk/';

// the output container

$out = array ();

// loop the directory

foreach ( glob ( $path . '*' ) AS $item )
{
if ( ! is_dir ( $item ) && ! in_array ( ( $file = basename ( $item ) ), $bad ) )
{
$out[] = array ( strtolower ( $file ), filemtime ( $item ), filesize ( $item ) );
}
}

// call the sort function

if ( ! empty ( $out ) )
{
usort ( $out, 'sort_array' );

print_r ( $out );
}
else
{
echo 'no files in directory: ' . $path;
}

?>
[/code]

printf
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.