Link to home
Start Free TrialLog in
Avatar of lnwright
lnwright

asked on

Sort a Directory Listing by Part of Filename in PHP

Dear Experts,

I want to use PHP to sort and display a directory listing of files based on part of the filename.

The file names contain 3  fields, SupplierName, InvNo & InvDate which are delimited by an underscore  eg SmithPartners_123_25-06-04.jpg.    I have attached some code which splits the name into the fields and displays them.

What I also want to do is have a combo box that lets the user sort the results by either SupplierName, InvNo or InvDate.

I am new to PHP so please keep the code well commented and as simple as possible.    Don't worry about formatting.
 
Thanks,


Lee.

<?php

//***Get the directory of files.
$handle=opendir('c:\\inetpub\wwwroot\reports\\Documents\SupplierInvoices');
while ($FileName = readdir($handle)){

//***Split them into field names using "_" delimiter
   $SplitFileName = explode("_", $FileName);      
   $SupplierName = $SplitFileName[0];
   $InvNo = $SplitFileName[1];
   $InvDate = $SplitFileName[2];

//***Display them
   echo $SupplierName, "   ", $InvNo, "    ", $InvDate, "<BR>";
}
closedir($handle);

?>
SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lnwright
lnwright

ASKER

Thanks Jamie,

A sort function looks like a good solution.    I just want to clarify though.     The combo box only contains a list of the methods to sort be eg it would only contain 3 items "Sort By Supplier Name", " Sort by InvNo" and "Sort by Date".   I want to display the results on the page rather than in a combo box.    

Also I was kind of hoping for an entire solution that I could just cut and paste into my page.

Regards,


Lee.
Not tried but I think it works (unless any typo). Please try and advice:

<?php

function SortArrayByColumn($array, $column)
{
    $again = true;

    while ($again) {
        $again = false;
        for ($i=0; $i<count($array)-1; $i++) {
             if ($array[$i][$column] > $array[$i+1][$column]) {
                  $temp = $array[$i];
                  $array[$i] = $array[$i+1];
                  $array[$i+1] = $temp;
                  $again = true;
             }
        }
    }
    return $array;
}

$array = array();

$handle=opendir('c:\\inetpub\wwwroot\reports\\Documents\SupplierInvoices');
while ($FileName = readdir($handle)) {
   $array[] = explode("_", $FileName);
}
closedir($handle);

if (unset(POST['order'])) {
     $order = 0;
} else
     $order = (int)POST['order'];

echo ('<form name="frmOrder" method="post" action="">');
echo ("<SELECT NAME=\"CodTurno\">");
echo ("<OPTION VALUE=\"0\">Sort By Supplier Name</OPTION>\n");
echo ("<OPTION VALUE=\"1\">Sort by InvNo</OPTION>\n");
echo ("<OPTION VALUE=\"2\">Sort by Date</OPTION>\n");
echo ('</SELECT>&nbsp;&nbsp;<INPUT TYPE=SUBMIT NAME="SUBMIT" VALUE="Change"></form>\n');

$array = SortArrayByColumn($array, $order);

for ($i=0; $i<count($array);$i++) {
      echo $array[$i][0], "   ", $array[$i][1], "    ", $array[$i][2], "<BR>";
}
?>
Something like this seems to be what you are looking for:


if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
      $file_names[] = $file;
      preg_match( "#(.+?)_(.+?)_(.+?).(.+?)$#is", $file, $parts );
      $SupplierName[] = $parts[1];
      $InvNo[] = $parts[2];
      $InvDate[] = $parts[3];
        }
    }
    closedir($handle);
}
if ($sortBy == "SupplierName") {
//To sort by SupplierName:
array_multisort($SupplierName, $file_names);
} elseif ($sortBy == "InvNo") {
//To sort by InvNo:
array_multisort($InvNo, $file_names);
} elseif ($sortBy == "InvDate") {
//To sort by InvDate:
array_multisort($InvDate, $file_names);
}

foreach ($file_names as $key => $value) {
echo "<img src=$file_names><br>";
}

Thanks Jaime,

I get this error.

Parse error: parse error, unexpected T_UNSET in C:\Inetpub\wwwroot\reports\GetDirectory1.php on line 29
Sorry,

This line:
     if (unset(POST['order'])) {
Should be:
     if (!isset(POST['order'])) {
Jaime,

Parse error: parse error, unexpected T_STRING, expecting T_VARIABLE or '$' in C:\Inetpub\wwwroot\reports\GetDirectory1.php on line 29
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Experts,

There is some good stuff here but I need a complete solution including the combo box (if that is generated from code).  Something that I can just paste into my code window and that will run.    Jaime's solution seems the closest to that so far but as mentioned there is a bug.  

Regards,



Lee.
<?php
if (!($action)) {
echo "Select sort type:
<form action=$PHP_SELF method=POST>
<input type=hidden name=action value=do_sort>
<select name=sortBy>
<option value=SupplierName>by SupplierName</option>
<option value=InvNo>by InvNo</option>
<option value=InvDate>by InvDate</option>
</select>
<input type=submit value=Go></form>";
} elseif ($action == "do_sort") {


if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
     $file_names[] = $file;
     preg_match( "#(.+?)_(.+?)_(.+?).(.+?)$#is", $file, $parts );
     $SupplierName[] = $parts[1];
     $InvNo[] = $parts[2];
     $InvDate[] = $parts[3];
        }
    }
    closedir($handle);
}
if ($sortBy == "SupplierName") {
//To sort by SupplierName:
array_multisort($SupplierName, $file_names);
} elseif ($sortBy == "InvNo") {
//To sort by InvNo:
array_multisort($InvNo, $file_names);
} elseif ($sortBy == "InvDate") {
//To sort by InvDate:
array_multisort($InvDate, $file_names);
}

foreach ($file_names as $key => $value) {
echo "<a href=$value>$value</a><br>";
}
}
?>
oh, set $dir to whatever the folder in question is.
Thanks kaitou,

It will be about 3 hours before I can test this out but looks good.

Regards,


Lee.
kaitou,

I gave it a try.   The combo box displays ok but when you click "go" it just says page not found.  No further error details.    

Lee.
change $PHP_SELF to what you named the script.
Thanks Kaitou,

I changed it to this:

<form action="GetDirectory2.php" method=POST>

but now I get this error:

Parse error: parse error, unexpected T_STRING, expecting ',' or ';' in C:\Inetpub\wwwroot\reports\GetDirectory2.php on line 4

Please advise.
Notice when you get an error that the errorline ends with a line number.
It would help if you showed us what that line looks like (plus the one in front of it at that is often where the error is). In this case that would be line 3 and 4 of your file GetDirectory2.php
JakobA,

Here is the source, there are no spaces above.

 <?php
if (!($action)) {
echo "Select sort type:
<form action="GetDirectory2.php", method=POST>
<input type=hidden name=action value=do_sort>
<select name=sortBy>
<option value=SupplierName>by SupplierName</option>
<option value=InvNo>by InvNo</option>
<option value=InvDate>by InvDate</option>
</select>
<input type=submit value=Go></form>";
} elseif ($action == "do_sort") {


$dir = "c:\\inetpub\wwwroot\reports\\Documents\SupplierInvoices";
if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
     $file_names[] = $file;
     preg_match( "#(.+?)_(.+?)_(.+?).(.+?)$#is", $file, $parts );
     $SupplierName[] = $parts[1];
     $InvNo[] = $parts[2];
     $InvDate[] = $parts[3];
        }
    }
    closedir($handle);
}
if ($sortBy == "SupplierName") {
//To sort by SupplierName:
array_multisort($SupplierName, $file_names);
} elseif ($sortBy == "InvNo") {
//To sort by InvNo:
array_multisort($InvNo, $file_names);
} elseif ($sortBy == "InvDate") {
//To sort by InvDate:
array_multisort($InvDate, $file_names);
}

foreach ($file_names as $key => $value) {
echo "<a href=$value>$value</a><br>";
}
}
?>
Ther error is in the string handeling. strings have quotes around them, and inside the string tha same kind of quotes may not be used.  you have "-s around the string (starting on line 3 and ending on line 11); but inside the string you also use "-s in the html attribute: action="GetDirectory2.php"  and that confuses php.
Use single quotes inside the string:
  <form action='GetDirectory2.php', method=POST>
Thanks JakobA,

That fixes the error message but nothing happens when you click on the go button.

Regards,



Lee.
Try:  

 <?php
if (!($_POST[action])) {
echo "Select sort type:
<form action='GetDirectory2.php' method=POST>
<input type=hidden name=action value=do_sort>
<select name=sortBy>
<option value=SupplierName>by SupplierName</option>
<option value=InvNo>by InvNo</option>
<option value=InvDate>by InvDate</option>
</select>
<input type=submit value=Go></form>";
} elseif ($_POST[action] == "do_sort") {


$dir = "/";
if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
     $file_names[] = $file;
     preg_match( "#(.+?)_(.+?)_(.+?).(.+?)$#is", $file, $parts );
     $SupplierName[] = $parts[1];
     $InvNo[] = $parts[2];
     $InvDate[] = $parts[3];
        }
    }
    closedir($handle);
}
if ($_POST[sortBy] == "SupplierName") {
//To sort by SupplierName:
array_multisort($SupplierName, $file_names);
} elseif ($_POST[sortBy] == "InvNo") {
//To sort by InvNo:
array_multisort($InvNo, $file_names);
} elseif ($_POST[sortBy] == "InvDate") {
//To sort by InvDate:
array_multisort($InvDate, $file_names);
}

foreach ($file_names as $key => $value) {
echo "<a href=$value>$value</a><br>";
}
}
?>
This gives me a directory of the root of the c drive and no combo box
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks to all who posted..   This was a difficult question.   Kaitou finally had a solution that worked for me.      Just one question.  How do I stop the combo box from dissapearing when the results display?
put a copy of  

echo "Select sort type:
<form action='GetDirectory2.php' method=POST>
<input type=hidden name=action value=do_sort>
<select name=sortBy>
<option value=SupplierName>by SupplierName</option>
<option value=InvNo>by InvNo</option>
<option value=InvDate>by InvDate</option>
</select>
<input type=submit value=Go></form>";

under

} elseif ($_POST[action] == "do_sort") {
Points already awarded, but how do I stop the combo box from disappearing when the results appear.     I want it to stay at the top of the page.

Thanks,


Lee.
just edit the code to what i said in my previous comment.
kaitou ,

Sorry I didn't notice your post above.    It works fine.   Thankyou.

Lee
Actually I just noticed a problem.     It now doesn't actually sort and the chosen sort method changes back to "Supplier Invoices"

Please advise.

Thanks,


Lee.
it should still do the sort as before, but the drop down box would show the default choices, there is no code there to get it to switch to the selected one.
OK Thanks