Pedro Graca wrote:
[Please don't snip attributions]
Alan Searle wrote:
Pedro Graca wrote:
uasort($dirlist, 'cmp_function');
and
function cmp_function($lhs, $rhs) {
if ($lhs['column'] < $rhs['column']) return 1;
return ($lhs['column'] == $rhs['column']) ? 0 : -1;
}
I would like to use your example but so far I can't get it to work.
Post *your* code.
Code posted below ...
In your example here do I
need to replace the word 'column' with the name of the column that I
want to sort on? (that's what I did).
Yes, you did right.
And what are the parameters $lhs and $rhs (left hand side & right hand
side?). I don't need to change these, do I?
You don't need to change them. You may want to rename them to something
more coherent with your naming structure.
And how about descending order?
That particular 'cmp_function' already does a descending comparison.
The ascending way returns -1 when $lhs < $rhs
Hi Pedro,
Many thanks for your help.
At the moment the sort does not seem to have any effect on the sequence.
Is the resorted data written back to the same array? Or should I be
reading the data from a new array somewhere?
Here is a copy of my code ...
<html>
<head>
<title>Dir Sort</title>
</head>
<script language="php">
print("start<br>");
// Get a directory listing into dirlist ...
$i=1;
$dir = getcwd();
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (filetype($dir . "/" . $file)=="dir" AND $file != "." AND
$file != "..") {
// print("$file<br>");
$dirlist["dirid"][$i]=$i;
$dirlist["dirname"][$i]=$file;
$direxp=explode("_",$file); // replace underscore with blanks here
$dirlist["dirstrip"][$i]=implode(" ",$direxp);
$dirlist["dirfull"][$i]=$dir . "/" . $file;
$i++;
}
}
closedir($dh);
}
// run the uasort ...
$success = uasort($dirlist, 'cmp_function');
// print("success " . $success);
// loop through the array and print the result ...
$j=1;
For ($j=1; $j<=$i - 1; $j++) {
print($dirlist["dirid"][$j] . "/" . $dirlist["dirstrip"][$j] . "/"
.. $dirlist["dirname"][$j] . "<br>");
}
// callback function (dirstrip is the column to sort on) ...
function cmp_function($lhs, $rhs) {
if ($lhs['dirstrip'] < $rhs['dirstrip']) return 1;
return ($lhs['dirstrip'] == $rhs['dirstrip']) ? 0 : -1;
}
?>
</script>
</body>
</html>