Page 1 of 1

Sorting complex arrays

Posted: Sun Apr 30, 2006 1:47 pm
by alex.barylski
Having never dealt with any of the array sorting functions I assume they are mostly for sorting simple, single-dimension arrays???

Anyways, here is my problem I am hoping can be solved using built-in functionality as opposed to me writting all the sorting code by hand :)

I have any array which looks like this:

Code: Select all

Array
(
    [0] => Array
        (
            [fname] => George 
            [lname] => Lucas
            [time] => 1
        )

    [1] => Array
        (
            [fname] => Alexander
            [lname] => Gallagher
            [time] => 2
        )

    [2] => Array
        (
            [fname] => Matthew
            [lname] => Black
            [time] => 3
        )

)
The array name is $arr_test for the sake of this disscussion...

Is there a way I can specify which column I want sorted using builtin array functions?

Heres the catch...if I sort by time in ascending order...I need the parent array indicies to change as well, so sorting the above array would return the same as above...but descending

Code: Select all

Matthew, Black, 3


would become index ONE...

It appears as though I will need to write this manually from what I can tell by quickly glancing at the array sorting functions, they would just sort the columns and NOT reorder the parent array indicies, thus jumbling the data..???

Cheers :)

Posted: Sun Apr 30, 2006 1:51 pm
by Chris Corbyn
You'll need to write your own custom sort. It shouldn't be too tricky.

array_multisort() will not do what you want in case anybody is thinking it will.

Posted: Sun Apr 30, 2006 1:55 pm
by alex.barylski
d11wtq wrote:You'll need to write your own custom sort. It shouldn't be too tricky.

array_multisort() will not do what you want in case anybody is thinking it will.
Hey man, thanks for the heads up :)

I didn't think it would as from what I can tell it appears to sort *just* the columns and doesn't bother to re-arranage indicies...

I really hate writting sorting code... :P

Bummer :)

Posted: Mon May 01, 2006 6:03 am
by Ollie Saunders
iterate through the array in the order it is in now creating a new array that uses the data you want to index by as the key then use ksort() or krsort() to order it by the keys you just entered. Like this:

Code: Select all

$original; // your array structure as it is
$array = array(); // the new version
foreach($original as $value) {
   $array[$value['fname']] = array('lname'=>$value['lname'],'time'=>$value['time']);
}
ksort($array);
As for your catch:

Code: Select all

$array; // created earlier using the technique i describe at the beginning of this post
$theCatch = array();
foreach($array as $key => $value) {
   $theCatch [] = array($value, 'time' => $key);
}
give it a go.