473,386 Members | 1,832 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,386 software developers and data experts.

Sorting arrays

I'm having some trouble understanding what is happening with some array
sorting functions. In all cases, my compare function is:
function compare($x, $y)
{
if ( $x[1] == $y[1] )
return 0;
else if ( $x[1] < $y[1] )
return -1;
else
return 1;
}
I started with this:
$contents = array( array( 'TIR', 'Tires', 100 ),
array( 'OIL', 'Oil', 10 ),
array( 'SPK', 'Spark Plugs', 4 ) );
echo '<br>XXX<br>';
foreach($contents as $r) {
var_export($r);
echo '<br>';
}
echo '<br>YYY<br>';
uasort($contents, 'compare');
foreach($contents as $r) {
var_export($r);
echo '<br>';
}
And the output, whether I use usort or uasort is always:
XXX
array ( 0 => 'TIR', 1 => 'Tires', 2 => 100, )
array ( 0 => 'OIL', 1 => 'Oil', 2 => 10, )
array ( 0 => 'SPK', 1 => 'Spark Plugs', 2 => 4, )

YYY
array ( 0 => 'OIL', 1 => 'Oil', 2 => 10, )
array ( 0 => 'SPK', 1 => 'Spark Plugs', 2 => 4, )
array ( 0 => 'TIR', 1 => 'Tires', 2 => 100, )
But if I use uksort I get:
XXX
array ( 0 => 'TIR', 1 => 'Tires', 2 => 100, )
array ( 0 => 'OIL', 1 => 'Oil', 2 => 10, )
array ( 0 => 'SPK', 1 => 'Spark Plugs', 2 => 4, )

YYY
array ( 0 => 'SPK', 1 => 'Spark Plugs', 2 => 4, )
array ( 0 => 'OIL', 1 => 'Oil', 2 => 10, )
array ( 0 => 'TIR', 1 => 'Tires', 2 => 100, )

But I cannot see why I get this reversal of order???

I then tried:
$contents = array( array( c=>'TIR', d=>'Tires', p=>100 ),
array( c=>'OIL', d=>'Oil', p=>10 ),
array( c=>'SPK', d=>'Spark Plugs', p=>4 ) );

echo '<br>XXX<br>';
foreach($contents as $r) {
var_export($r);
echo '<br>';
}
echo '<br>YYY<br>';
uksort($contents, 'compare');
foreach($contents as $r) {
var_export($r);
echo '<br>';
}

And this time the output, whether I use usort, uasort or uksort is always:
XXX
array ( 'c' => 'TIR', 'd' => 'Tires', 'p' => 100, )
array ( 'c' => 'OIL', 'd' => 'Oil', 'p' => 10, )
array ( 'c' => 'SPK', 'd' => 'Spark Plugs', 'p' => 4, )

YYY
array ( 'c' => 'SPK', 'd' => 'Spark Plugs', 'p' => 4, )
array ( 'c' => 'OIL', 'd' => 'Oil', 'p' => 10, )
array ( 'c' => 'TIR', 'd' => 'Tires', 'p' => 100, )

Finally I tried:
$contents = array( array( c=>'TIR', d=>'Tires', p=>100 ),
array( c=>'OIL', a=>'Oil', p=>10 ),
array( c=>'SPK', z=>'Spark Plugs', p=>4 ) );

echo '<br>XXX<br>';
foreach($contents as $r) {
var_export($r);
echo '<br>';
}
echo '<br>YYY<br>';
uksort($contents, 'compare');
foreach($contents as $r) {
var_export($r);
echo '<br>';
}
And once again, the outputs with usort, uasort or uksort is always:
XXX
array ( 'c' => 'TIR', 'd' => 'Tires', 'p' => 100, )
array ( 'c' => 'OIL', 'd' => 'Oil', 'p' => 10, )
array ( 'c' => 'SPK', 'd' => 'Spark Plugs', 'p' => 4, )

YYY
array ( 'c' => 'SPK', 'd' => 'Spark Plugs', 'p' => 4, )
array ( 'c' => 'OIL', 'd' => 'Oil', 'p' => 10, )
array ( 'c' => 'TIR', 'd' => 'Tires', 'p' => 100, )

Can someone explain why none of the cases will sort the associative array by
the second "column" and how I can find examples that will sow the
differences between the 3 sort functions???

TIA
Paul
May 21 '06 #1
11 1927
I understand a bit more about it now, having tried something else, but I
still can't find a difference between usort and uasort and neither can I
figure out how to use uksort?
May 21 '06 #2
Paul Lautman wrote:
I understand a bit more about it now, having tried something else,
but I still can't find a difference between usort and uasort and
neither can I figure out how to use uksort?


What is going wrong in the code from your previous post is that you are
using numeric indexes on associative arrays, contained in $x and $y, which
are using keys instead.

Compare the following implementation with the one from your previous post:

function compare($a, $b) {
list(,$var_a) = array_values($a);
list(,$var_b) = array_values($b);
if ($var_a == $var_b) return 0;
return $var_a < $var_b ? -1 : 1;
}

As you will see, list extracts the value from the second index from the
array returned by array_values when applied to $a and $b.

The difference between usort and uasort, is that the latter preserves the
index association, while the first doesn't. As an example, with usort, the
result will always be:

array( 0 => ..., 1 => ....);

while with uasort, depending on the structure of the original array, the
result can be:

array( 1 => ..., 0 => ....);

The uksort function uses the keys/indexes, while the uasort function uses
the values for sorting. For the array structure you've posted, uksort
appears to be useless.
JW
May 21 '06 #3
On Sat, 20 May 2006 23:46:54 +0100, Paul Lautman wrote:
function compare($x, $y)
{
if ( $x[1] == $y[1] )
return 0;
else if ( $x[1] < $y[1] )
return -1;
else
return 1;
}


Try with this:

function compare($x, $y)
{
GLOBAL $contents;
if ($contents[$x] == $contents[$y])
return(0);
else
return ($contents[$x]<$contents[$y]? -1:1);

}

--
http://www.mgogala.com

May 21 '06 #4
Janwillem Borleffs wrote:
Paul Lautman wrote:
I understand a bit more about it now, having tried something else,
but I still can't find a difference between usort and uasort and
neither can I figure out how to use uksort?


What is going wrong in the code from your previous post is that you
are using numeric indexes on associative arrays, contained in $x and
$y, which are using keys instead.

Compare the following implementation with the one from your previous
post:
function compare($a, $b) {
list(,$var_a) = array_values($a);
list(,$var_b) = array_values($b);
if ($var_a == $var_b) return 0;
return $var_a < $var_b ? -1 : 1;
}

As you will see, list extracts the value from the second index from
the array returned by array_values when applied to $a and $b.

The difference between usort and uasort, is that the latter preserves
the index association, while the first doesn't. As an example, with
usort, the result will always be:

array( 0 => ..., 1 => ....);

while with uasort, depending on the structure of the original array,
the result can be:

array( 1 => ..., 0 => ....);

The uksort function uses the keys/indexes, while the uasort function
uses the values for sorting. For the array structure you've posted,
uksort appears to be useless.
JW

Yeah I worked out the indexes problem.

Can you give me an example of where usort and uasort give different outputs
and how uksort would be used?

May 21 '06 #5
Mladen Gogala wrote:
On Sat, 20 May 2006 23:46:54 +0100, Paul Lautman wrote:
function compare($x, $y)
{
if ( $x[1] == $y[1] )
return 0;
else if ( $x[1] < $y[1] )
return -1;
else
return 1;
}


Try with this:

function compare($x, $y)
{
GLOBAL $contents;
if ($contents[$x] == $contents[$y])
return(0);
else
return ($contents[$x]<$contents[$y]? -1:1);

}


What is this supposed to achieve?
May 21 '06 #6
Paul Lautman wrote:
Can you give me an example of where usort and uasort give different
outputs and how uksort would be used?


function cmp($a, $b) {
if ($a == $b) return 0;
return $a < $b ? -1 : 1;
}

$array = array('b' => 200, 'a' => 50, 'A' => 100);
$usort = $uasort = $uksort = $array;

print 'original array:<br>';
print_r($array);

print '<hr>usort: sorted by value, keys are not preserved:<br>';
usort($usort, 'cmp');
print_r($usort);

print '<hr>uasort: sorted by value, keys are preserved:<br>';
uasort($uasort, 'cmp');
print_r($uasort);

print '<hr>uksort: sorted by key;<br>';
print '"A" put before "a" because of its lower ASCII value:<br>';
uksort($uksort, 'cmp');
print_r($uksort);
JW
May 21 '06 #7
Janwillem Borleffs wrote:
Paul Lautman wrote:
Can you give me an example of where usort and uasort give different
outputs and how uksort would be used?


function cmp($a, $b) {
if ($a == $b) return 0;
return $a < $b ? -1 : 1;
}

$array = array('b' => 200, 'a' => 50, 'A' => 100);
$usort = $uasort = $uksort = $array;

print 'original array:<br>';
print_r($array);

print '<hr>usort: sorted by value, keys are not preserved:<br>';
usort($usort, 'cmp');
print_r($usort);

print '<hr>uasort: sorted by value, keys are preserved:<br>';
uasort($uasort, 'cmp');
print_r($uasort);

print '<hr>uksort: sorted by key;<br>';
print '"A" put before "a" because of its lower ASCII value:<br>';
uksort($uksort, 'cmp');
print_r($uksort);
JW


Cheers for that, do you also know why I see the oder reversal (see the first
post)?
May 21 '06 #8
Paul Lautman wrote:
Cheers for that, do you also know why I see the oder reversal (see
the first post)?


In your original compare function, the passed numeric indexes are converted
to strings (because of the var[1] syntax, which is a deprecated use of
var{1} with scalars) of which you are requesting the second character that
doesn't exist. In effect, you are comparing '' with '', which is equal.

If you look at the sequences passed, from the original array, index 1 is
compared to index 0 and index 2 is compared to index 1.

The result of the first comparison would be:

1 => array( 'OIL', 'Oil', 10 )
0 => array( 'TIR', 'Tires', 100 )

The result of the second comparison would be:

2 => array( 'SPK', 'Spark Plugs', 4 )
1 => array( 'OIL', 'Oil', 10 )
0 => array( 'TIR', 'Tires', 100 )

So, the reversal effect is the result of the first argument passed to the
compare function being considered to be equal to the second one and they are
therefore sorted in the order they where passed.
JW
May 21 '06 #9
Janwillem Borleffs wrote:
In your original compare function, the passed numeric indexes are
converted to strings (because of the var[1] syntax, which is a
deprecated use of var{1} with scalars)


"which is a deprecated use of var{1} with scalars" should read:
"which is a deprecated use of var{1} on strings"

JW
May 21 '06 #10
Janwillem Borleffs wrote:
Paul Lautman wrote:
Cheers for that, do you also know why I see the oder reversal (see
the first post)?


In your original compare function, the passed numeric indexes are
converted to strings (because of the var[1] syntax, which is a
deprecated use of var{1} with scalars) of which you are requesting
the second character that doesn't exist. In effect, you are comparing
'' with '', which is equal.
If you look at the sequences passed, from the original array, index 1
is compared to index 0 and index 2 is compared to index 1.

The result of the first comparison would be:

1 => array( 'OIL', 'Oil', 10 )
0 => array( 'TIR', 'Tires', 100 )

The result of the second comparison would be:

2 => array( 'SPK', 'Spark Plugs', 4 )
1 => array( 'OIL', 'Oil', 10 )
0 => array( 'TIR', 'Tires', 100 )

So, the reversal effect is the result of the first argument passed to
the compare function being considered to be equal to the second one
and they are therefore sorted in the order they where passed.
JW


Thank you for your very full and thorough explanation.
May 21 '06 #11
On Sun, 21 May 2006 13:02:53 +0100, Paul Lautman wrote:
What is this supposed to achieve?


Sort hash keys according to the hash values.

--
http://www.mgogala.com

May 21 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Paul Kirby | last post by:
Hello All I am trying to update me code to use arrays to store a group of information and I have come up with a problem sorting the multiple array :( Array trying to sort: (7 arrays put into...
7
by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) ...
22
by: mike | last post by:
If I had a date in the format "01-Jan-05" it does not sort properly with my sort routine: function compareDate(a,b) { var date_a = new Date(a); var date_b = new Date(b); if (date_a < date_b)...
7
by: Karin Jensen | last post by:
Hi I am running a PHP program that connects to an Access 2000 database via ODBC: $results = odbc_exec($connection_id, $sql_select); Is it possible to sort the contents of $results? I wish to...
16
by: aruna | last post by:
Given a set of integers, how to write a program in C to sort these set of integers using C, given the following conditions a. Do not use arrays b. Do not use any comparison function like if/then...
23
by: yatindran | last post by:
hai this is my 2d array. int a = { {5,2,20,1,30,10}, {23,15,7,9,11,3}, {40,50,34,24,14,4}, {9,10,11,12,13,14}, {31,4,18,8,27,17}, {44,32,13,19,41,19}, {1,2,3,4,5,6},
10
by: Roy Gourgi | last post by:
Hi, How would I sort an array? TIA Roy
3
by: SneakyElf | last post by:
i am very green with c++ so i get stuck on very simple things anyway, i need to write a program that would read data from file (containing names of tv shows and their networks) one line at a time...
3
KevinADC
by: KevinADC | last post by:
If you are entirely unfamiliar with using Perl to sort data, read the "Sorting Data with Perl - Part One and Two" articles before reading this article. Beginning Perl coders may find this article...
5
by: lemlimlee | last post by:
hello, this is the task i need to do: For this task, you are to develop a Java program that allows a user to search or sort an array of numbers using an algorithm that the user chooses. The...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...

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.