Forum Moderators: coopster

Message Too Old, No Replies

is there an ultimate PHP 3d array sort function?

         

Crump

6:49 pm on Sep 2, 2010 (gmt 0)

10+ Year Member



This is for a sports standings script.

I have been scouring the next for a 3D array sort tool. I have found a decent one, but it looks one item... the ability to choose between DESC/ASC per column.

This is the function I have been using:


function sortArray($data, $field) {
if(!is_array($field)) $field = array($field);
usort($data, function($a, $b) use($field) {
$retval = 0;
foreach($field as $fieldname) {
if($retval == 0) $retval = strnatcmp($a[$fieldname],$b[$fieldname]);
}
return $retval;
});
return array_reverse($data);
}

(please note, I had to stick the array_reverse in there)

For each user, my array features:

$standings_array[$thisuser]['W']
$standings_array[$thisuser]['L']
$standings_array[$thisuser]['T']
$standings_array[$thisuser]['perc']
$standings_array[$thisuser]['total']

I call it like this:

$sorted_array = sortArray($standings_array, array('perc', 'total', 'L', 'T'));


The above function generates this:


user4 / 1 / 0 / 0 / 1.000 / 50
user2 / 1 / 0 / 0 / 1.000 / 35
user3 / 1 / 0 / 0 / 1.000 / 22
user1 / 0 / 1 / 0 / 0.000 / 59
user5 / 0 / 1 / 0 / 0.000 / 50
user7 / 0 / 1 / 0 / 0.000 / 41
user6 / 0 / 0 / 1 / 0.000 / 32
user8 / 0 / 0 / 1 / 0.000 / 32


However, in the script I am building, the LOWER the total points the better. As you can see, it is ranked first winning percentage, then total points. However, like I said, I need the LOWER total points to go on top.

3D arrays have always confused me. Can anyone give me some guidance?

Is there some ultimate sorting function somewhere, where I can switch columns from ASC/DESC (like in MySQL)

coopster

8:25 pm on Dec 15, 2010 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Not that I'm aware, but you could build your own, that's for sure.

As far as what you have here, it seems all you need to do is reverse the return value of strnatcmp(). So, check the value returned by the function and reverse the values. Voila, reversed sort. You merely need to add the ASC/DESC to your custom function, possibly set the default and handle the logic in the function accordingly.