By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,304 Members | 1,253 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,304 IT Pros & Developers. It's quick & easy.

Multi-sorting arrays ...

P: n/a
I have been trying to get an array to sort on a particular column and
have been having problems with my main key ...

array_multisort($dirlist["dirname"], SORT_DESC, SORT_STRING);

This function takes an array ($dirlist) which has been loaded with a
directory listing where each directory has its own index number
("dirid") and displays the listing in descending order by name
("dirname"). This works fine for the sorting of the names but the index
number is reallocated (I assume because it is numeric) and I lose my
link to the directory. arrgghh!

How can I keep the rows 'together' and make sure that the index number
and the name remain consistant?

Any tips or snippets of syntax would be a great help.

Regards,
Alan Searle.
Jul 17 '05 #1
Share this Question
Share on Google+
11 Replies


P: n/a
Alan Searle wrote:
I have been trying to get an array to sort on a particular column and
have been having problems with my main key ...

array_multisort($dirlist["dirname"], SORT_DESC, SORT_STRING);


I've never used array_multisort() and I don't want to dive into the docs
right now.

Do you really need array_multisort() ?

uasort($dirlist, 'cmp_function');

and

function cmp_function($lhs, $rhs) {
if ($lhs['column'] < $rhs['column']) return 1;
return ($lhs['column'] == $rhs['column']) ? 0 : -1;
}
--
USENET would be a better place if everybody read: | to email me: use |
http://www.catb.org/~esr/faqs/smart-questions.html | my name in "To:" |
http://www.netmeister.org/news/learn2quote2.html | header, textonly |
http://www.expita.com/nomime.html | no attachments. |
Jul 17 '05 #2

P: n/a

"Alan Searle" <aj*******@xxxxyahoo.com> wrote in message
news:cc**********@newsreader3.netcologne.de...
I have been trying to get an array to sort on a particular column and
have been having problems with my main key ...

array_multisort($dirlist["dirname"], SORT_DESC, SORT_STRING);

This function takes an array ($dirlist) which has been loaded with a
directory listing where each directory has its own index number
("dirid") and displays the listing in descending order by name
("dirname"). This works fine for the sorting of the names but the index
number is reallocated (I assume because it is numeric) and I lose my
link to the directory. arrgghh!

How can I keep the rows 'together' and make sure that the index number
and the name remain consistant?

Any tips or snippets of syntax would be a great help.

Regards,
Alan Searle.

Jul 17 '05 #3

P: n/a
"Alan Searle" <aj*******@xxxxyahoo.com> wrote in message
news:cc**********@newsreader3.netcologne.de...
I have been trying to get an array to sort on a particular column and
have been having problems with my main key ...

array_multisort($dirlist["dirname"], SORT_DESC, SORT_STRING);

This function takes an array ($dirlist) which has been loaded with a
directory listing where each directory has its own index number
("dirid") and displays the listing in descending order by name
("dirname"). This works fine for the sorting of the names but the index
number is reallocated (I assume because it is numeric) and I lose my
link to the directory. arrgghh!


I have run into that problem before too. According to the manual
array_multisort() is supposed to maintain key association but in actual use
it changes the key. Use arsort() instead.
Jul 17 '05 #4

P: n/a
Chung Leong wrote:
"Alan Searle" <aj*******@xxxxyahoo.com> wrote in message
news:cc**********@newsreader3.netcologne.de...
I have been trying to get an array to sort on a particular column and
have been having problems with my main key ...

array_multisort($dirlist["dirname"], SORT_DESC, SORT_STRING);

This function takes an array ($dirlist) which has been loaded with a
directory listing where each directory has its own index number
("dirid") and displays the listing in descending order by name
("dirname"). This works fine for the sorting of the names but the index
number is reallocated (I assume because it is numeric) and I lose my
link to the directory. arrgghh!


I have run into that problem before too. According to the manual
array_multisort() is supposed to maintain key association but in actual use
it changes the key. Use arsort() instead.

I had a look at arsort() but it seems to cover single dimension arrays.
Can I adapt it to work with a multi-dimension array?

Thanks for your help.

Rgds,
Alan.
Jul 17 '05 #5

P: n/a
SNIP ...

Do you really need array_multisort() ?
Yes, array_multisort() seems to be a 'pain in the bottom' ... it messes
up the key relationships. Arrgghh!
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. I am
not sure how 'callback' functions operate: 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).

And what are the parameters $lhs and $rhs (left hand side & right hand
side?). I don't need to change these, do I?

And how about descending order? I would just need to change '<' to '>',
wouldn't I?

Many thanks,
Alan Searle
Jul 17 '05 #6

P: n/a
[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.
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
--
USENET would be a better place if everybody read: | to email me: use |
http://www.catb.org/~esr/faqs/smart-questions.html | my name in "To:" |
http://www.netmeister.org/news/learn2quote2.html | header, textonly |
http://www.expita.com/nomime.html | no attachments. |
Jul 17 '05 #7

P: n/a
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>
Jul 17 '05 #8

P: n/a
Alan Searle wrote:
// Get a directory listing into dirlist ...
$i=1;
Why not 0?
$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;
Aha! :)

IMHO you're building the array the wrong way around.

This way to do it, will not work with uasort() ... maybe
array_multisort(), I don't know.

If you do

$dirlist[$i]['dirid'] = $i;
$dirlist[$i]['dirname'] = $file;
// ...

instead, uasort() will work correctly (of course you'll have to change
your code to reflect the change in the array).

$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++) {
I prefer a foreach() loop, but this also works.
print($dirlist["dirid"][$j] . "/" . $dirlist["dirstrip"][$j] . "/"
. $dirlist["dirname"][$j] . "<br>");
}

(snip)

Your $dirlist array has 4 elements (their keys are "dirid", "dirname",
....). Each of these elements is itself another array with as many
elements as there are files in the directory.

If you change the way you build the array you get an array with as many
elements as there are files in the directory, in which every element is
itself another array with keys "dirid", ...
HTH

--
USENET would be a better place if everybody read: | to email me: use |
http://www.catb.org/~esr/faqs/smart-questions.html | my name in "To:" |
http://www.netmeister.org/news/learn2quote2.html | header, textonly |
http://www.expita.com/nomime.html | no attachments. |
Jul 17 '05 #9

P: n/a
Pedro Graca wrote:
Alan Searle wrote:
// Get a directory listing into dirlist ...
$i=1;

Why not 0?

$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;

Aha! :)

IMHO you're building the array the wrong way around.

This way to do it, will not work with uasort() ... maybe
array_multisort(), I don't know.

If you do

$dirlist[$i]['dirid'] = $i;
$dirlist[$i]['dirname'] = $file;
// ...

instead, uasort() will work correctly (of course you'll have to change
your code to reflect the change in the array).
$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++) {

I prefer a foreach() loop, but this also works.

print($dirlist["dirid"][$j] . "/" . $dirlist["dirstrip"][$j] . "/"
. $dirlist["dirname"][$j] . "<br>");
}


(snip)

Your $dirlist array has 4 elements (their keys are "dirid", "dirname",
...). Each of these elements is itself another array with as many
elements as there are files in the directory.

If you change the way you build the array you get an array with as many
elements as there are files in the directory, in which every element is
itself another array with keys "dirid", ...
HTH


Hi Pedro,

I had adapted my code (and reduced it a lot) but the sorting still
doesn't work. uasort seems to run successfully but the array still has
the old sort sequence.

I even tried adding 'x' to 'dirid' so that it was no longer a numeric.

Maybe you could take another quick look?

Many thanks,
Alan.

<html>
<head>
<title>Dir Sort</title>
</head>
<script language="php">

print("start<br>");

// Get a directory listing into dirlist ...
$i=0;
$dir = getcwd();

if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (filetype($dir . "/" . $file)=="dir" AND $file != "." AND
$file != "..") {
$dirlist[$i]['dirid']="x" . $i;
$dirlist[$i]['dirname']=$file;
$i++;
}
}
closedir($dh);
}

// run the uasort ...
$success = uasort($dirlist, 'cmp_function');

if ($success==true) {
print('array multisort successful<br>');
}

// loop through the array and print the result ...
For ($j=0; $j<$i; $j++) {
print($dirlist[$j]['dirid'] . "/" . $dirlist[$j]['dirname'] . "<br>");
}

// callback function (dirstrip is the column to sort on) ...
function cmp_function($lhs, $rhs) {
if ($lhs['dirname'] < $rhs['dirname']) return 1;
return ($lhs['dirname'] == $rhs['dirname']) ? 0 : -1;
}

?>

</script>
</body>
</html>
Jul 17 '05 #10

P: n/a
Alan Searle wrote:
I had adapted my code (and reduced it a lot) but the sorting still
doesn't work. uasort seems to run successfully but the array still has
the old sort sequence.

I even tried adding 'x' to 'dirid' so that it was no longer a numeric.
No need for that.

(snip) // run the uasort ...
$success = uasort($dirlist, 'cmp_function');


Aha! :-))
My error -- uasort *keeps* the associated keys, so that if you uasort()
the array

$a[0] = '4'; $a[1] = '1'; $a[2] = '2';

you get

$a[1] = '1'; $a[2] = '2'; $a[0] = '4';
// notice $a[0] in third place :)

instead of

$a[0] = '1'; $a[1] = '1'; $a[2] = '4';

just change the uasort() into usort() and it should be ok.

.... or print the array inside a foreach() loop :-)

Try this:

<?php
$a[2] = 'two';
$a[0] = 'zero';
$a[1] = 'one';

for ($i=0; $i<3; ++$i) echo $a[$i], ' ';
echo "\n<br/>\n";
foreach ($a as $v) echo $v, ' ';
?>

--
USENET would be a better place if everybody read: | to email me: use |
http://www.catb.org/~esr/faqs/smart-questions.html | my name in "To:" |
http://www.netmeister.org/news/learn2quote2.html | header, textonly |
http://www.expita.com/nomime.html | no attachments. |
Jul 17 '05 #11

P: n/a
Pedro Graca wrote:
Alan Searle wrote:
I had adapted my code (and reduced it a lot) but the sorting still
doesn't work. uasort seems to run successfully but the array still has
the old sort sequence.

I even tried adding 'x' to 'dirid' so that it was no longer a numeric.

No need for that.

(snip)
// run the uasort ...
$success = uasort($dirlist, 'cmp_function');

Aha! :-))
My error -- uasort *keeps* the associated keys, so that if you uasort()
the array

$a[0] = '4'; $a[1] = '1'; $a[2] = '2';

you get

$a[1] = '1'; $a[2] = '2'; $a[0] = '4';
// notice $a[0] in third place :)

instead of

$a[0] = '1'; $a[1] = '1'; $a[2] = '4';

just change the uasort() into usort() and it should be ok.

... or print the array inside a foreach() loop :-)

Try this:

<?php
$a[2] = 'two';
$a[0] = 'zero';
$a[1] = 'one';

for ($i=0; $i<3; ++$i) echo $a[$i], ' ';
echo "\n<br/>\n";
foreach ($a as $v) echo $v, ' ';
?>


Hi Pedro,

Yes, it worked! Many thanks.

And thanks for the little 'foreach' example. This helps me to 'get my
head around' some aspects of array handling.

Cheers,
Alan.
Jul 17 '05 #12

This discussion thread is closed

Replies have been disabled for this discussion.