Re: Sorting array data by week day order
| From: | David Otton | Date: | Thu, 22 May 2003 00:09:21 +0000 |
| Subject: | Re: Sorting array data by week day order | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-148479@lists.php.net to get a copy of this message | ||
On Thu, 22 May 2003 00:08:38 +0100, you wrote:
>It's an array of users and the amount of hours they have done in a working
>week. I am plotting the data to a graph using jpgraph and so need to data in
>day order. Is there a way to sort the data so I end up with this:
If you want an arbitary sort order, you need to apply your own comparison
function.
This can be acheived with a callback function. uksort() and it's brethren
allow you to do this.
It's pretty simple, so lets try an example...
<?
function day_compare ($a, $b) {
if ($a == $b) {
return(0);
}
switch ($a) {
case 'mon' : $adash = 1; break;
case 'tues' : $adash = 2; break;
case 'weds' : $adash = 3; break;
case 'thurs' : $adash = 4; break;
case 'fri' : $adash = 5; break;
case 'sat' : $adash = 6; break;
case 'sun' : $adash = 7; break;
}
switch ($b) {
case 'mon' : $bdash = 1; break;
case 'tues' : $bdash = 2; break;
case 'weds' : $bdash = 3; break;
case 'thurs' : $bdash = 4; break;
case 'fri' : $bdash = 5; break;
case 'sat' : $bdash = 6; break;
case 'sun' : $bdash = 7; break;
}
return ($adash > $bdash) ? 1 : -1;
}
$arr = array ('sat' => 0, 'tues' => 7, 'mon' => 2,
'thurs' => 4, 'weds' =>
3, 'fri' => 1, 'sun' => 0);
uksort ($arr, 'day_compare');
print_r($arr);
?>
That should get you started. Watch out for those *sort*() functions... they
sort arrays in place rather than returning a copy.