Re: Array Sort Tricky
| From: | John McKown | Date: | Fri, 15 Sep 2000 23:45:15 +0000 |
| Subject: | Re: Array Sort Tricky | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-16997@lists.php.net to get a copy of this message | ||
On Fri, 15 Sep 2000, Matt Friedman wrote:
> Hello!
>
> I have an associative array where userID is the key, and each key contains
> an array.
> So, Score is array[0] and Date is array[1] (see below).
>
> that is:
> $arr[userID] = array(Score, Date);
>
> Output looks like below:
>
> UserID: 10
> Score: 4
> Date: 852105600
>
> UserID: 12
> Score: 5
> Date: 852105600
>
> UserID: 14
> Score: 3
> Date: 946713600
>
> UserID: 16
> Score: 3
> Date: 852105600
>
> I would like to order by score, and then order by Date, but ordering by date
> must occur without messing up the order by score order.
>
> So, the desired output would be:
>
> UserID: 12
> Score: 5
> Date: 852105600
>
> UserID: 10
> Score: 4
> Date: 852105600
>
> UserID: 14
> Score: 3
> Date: 946713600
>
> UserID: 16
> Score: 3
> Date: 852105600
>
>
> Problem is, I don't know how to do it.
> Any help?
> Many thanks!
> matt.
The following appear to do what you want (with your test data "hard
coded" into the test program).
<?php
function docmp($a,$b) {
// test score in a versus score in b
if ($a[0] > $b[0]) return -1; /* a.score > b.score */
if ($a[0] < $b[0]) return 1; /* a.score < b.score */
// well, the scores are equal, test the dates
if ($a[1] > $b[1]) return -1; /* a.date > b.date */
if ($a[1] < $b[1]) return 1; /* a.date < b.date */
// well, they are the same, so say so.
return 0;
}
$arr['10']=array(4,852105600);
$arr['12']=array(5,852105600);
$arr['14']=array(3,946713600);
$arr['16']=array(3,852105600);
echo '<br>Before sort<br>';
while (list($key, $value) = each($arr)) {
echo $key." ".$value[0]." ".$value[1];
echo '<br>';
}
echo '<br>After sort.<br>';
uasort($arr,docmp);
while (list($key, $value) = each($arr)) {
echo $key." ".$value[0]." ".$value[1];
echo '<br>';
}
?>