473,395 Members | 1,999 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Multi-sorting arrays ...

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
11 2068
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

"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
"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
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
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
[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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
by: ajikoe | last post by:
Hello, Is anyone has experiance in running python code to run multi thread parallel in multi processor. Is it possible ? Can python manage which cpu shoud do every thread? Sincerely Yours,...
4
by: Frank Jona | last post by:
Intellisense with C# and a multi-file assembly is not working. With VB.NET it is working. Is there a fix availible? We're using VisualStudio 2003 Regards Frank
12
by: * ProteanThread * | last post by:
but depends upon the clique: ...
0
by: frankenberry | last post by:
I have multi-page tiff files. I need to extract individual frames from the multi-page tiffs and save them as single-page tiffs. 95% of the time I receive multi-page tiffs containing 1 or more black...
6
by: cody | last post by:
What are multi file assemblies good for? What are the advantages of using multiple assemblies (A.DLL+B.DLL) vs. a single multi file assembly (A.DLL+A.NETMODULE)?
4
by: mimmo | last post by:
Hi! I should convert the accented letters of a string in the correspondent letters not accented. But when I compile with -Wall it give me: warning: multi-character character constant Do the...
5
by: Shane Story | last post by:
I can seem to get the dimensions of a frame in a multiframe tiff. After selecting activeframe, the Width/Height is still really much larger than the page's actual dimensions. When I split a...
5
by: bobwansink | last post by:
Hi, I'm relatively new to programming and I would like to create a C++ multi user program. It's for a project for school. This means I will have to write a paper about the theory too. Does anyone...
0
by: Sabri.Pllana | last post by:
We apologize if you receive multiple copies of this call for papers. *********************************************************************** 2008 International Workshop on Multi-Core Computing...
1
by: mknoll217 | last post by:
I am recieving this error from my code: The multi-part identifier "PAR.UniqueID" could not be bound. The multi-part identifier "Salary.UniqueID" could not be bound. The multi-part identifier...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.