Click to See Complete Forum and Search --> : Array Sorting


Beach Bum
01-26-2005, 03:21 PM
A simple example. I am loading a multi-dim array through a loop as follows:

$array[] = array( $1, $2, $3 );

$array ends up with some number of rows - say 50 - it doesn't matter how many.

Now I want to sort $array in the sequence of $3 rather than the order in which $array was loaded - preserving the integrity of $1 $2 $3 in each row of $array.

This must be simple, but I am not seeing it on php.net. All the array sort options are confusing.

NogDog
01-26-2005, 04:01 PM
$array[] = array( $1, $2, $3 );

I'm confused - that looks like a single-dimension array to me. :confused:

Anyway, asort() (http://www.php.net/manual/en/function.asort.php) and arsort() (http://www.php.net/manual/en/function.arsort.php) will maintain the key=>value relationships.

Beach Bum
01-26-2005, 04:19 PM
Originally posted by NogDog
[B]I'm confused - that looks like a single-dimension array to me. :confused:That is all a multi-dimensional array is - an array within each array row. At least that is the what the books say. But in any event, that is what I am creating. Each $array row contains another array.

I will look again at asort() and arsort()

Edit >>

Don't see how they will do what I am after. I don't see how to tell it what to sort on (in my example above element $3).

I thought about loading $array with the value I want to sort by - like $array[$3] then using ksort(), but there may be duplicate $3 values.

NogDog
01-26-2005, 04:24 PM
Ahhh...so $1, $2, and $3 are each arrays, I presume? I've never tried sorting multi-dim arrays in PHP. Looks like array_multisort() (http://www.php.net/manual/en/function.array-multisort.php) may be just the ticket.

Beach Bum
01-26-2005, 04:33 PM
Originally posted by NogDog
Ahhh...so $1, $2, and $3 are each arrays, I presume? I've never tried sorting multi-dim arrays in PHP. Looks like array_multisort() (http://www.php.net/manual/en/function.array-multisort.php) may be just the ticket.
No . . . $1 $2 $3 are elements. $array is an array. each row of that array is being loaded with an array( $1, $2, $3). I just did not show you the looping operation that loads the $array[]

I have also looked at array_multisort and cannot figure out how to make it do what I want. I sorts the arrays within the array. I want to sort the array rows based on an element in the second array.

Beach Bum
01-26-2005, 04:52 PM
OK, I figured out how to load the array key without duplicates, making $key a derivitive of $3 - so now I can just sort on the key.

$array[$key] = array( $1, $2, $3 )

So now I can use ksort()

Now I need to figure out how to do a reverse ksort()

ShrineDesigns
01-26-2005, 04:56 PM
krsort() (http://www.php.net/manual/en/unction.krsort.php)

Beach Bum
01-26-2005, 05:09 PM
Originally posted by ShrineDesigns
krsort() (http://www.php.net/manual/en/unction.krsort.php) Thanks - that does it.