Thursday, February 02, 2006

Bug of sorting by date

One more bug, and in familiar place - in sorting. Binary-safe comparison of values has not coped with correct sorting according to a kind "21/01/2006".

How to struggle? If your purpose stands sorting by field DATE, instead of DATE_CREATE or ID, i.e. during addition of news you add news backdating or on the contrary, you need this cnahges.

So, we open/usr/system/common_extfunctions.inc.php (for the greater clearness in an example I use a standard file, instead of that I already corrected as it was described earlier in it blog). Further we find there such lines:

if(!defined("cmp_indexasc")) {
function cmp_indexasc($a, $b) {
global $sapi_obj;
$index = $sapi_obj->env["index"];
return strcmp($a[$index], $b[$index]);
}
define("cmp_indexasc", 1);
}

if(!defined("cmp_indexdesc")) {
function cmp_indexdesc($a, $b) {
global $sapi_obj;
$index = $sapi_obj->env["index"];
return strcmp($a[$index], $b[$index]);
}
define("cmp_indexdesc", 1);
}
By the way pay attention, here you can see one more bug which is obvious - and in case ASC sorting and in case DESC the same sorting is made. But now we will correct all this bugs. We replace this with the following:

if(!defined("cmp_indexasc")) {
function cmp_indexasc($a, $b) {
global $sapi_obj;
$index = $sapi_obj->env["index"];
if($index=='ID')
return ($a[$index] > $b[$index]) ? -1 : 1;
else if ($index=='DATE'){
$date_a=explode('/',$a[$index]);
$date_b=explode('/',$b[$index]);
$a_index=mktime (0,0,0,$date_a[1], $date_a[0], $date_a[2]);
$b_index=mktime (0,0,0, $date_b[1], $date_b[0], $date_b[2]);
return strcmp($a_index,$b_index);
}
else
return strcmp($a[$index], $b[$index]);
}
define("cmp_indexasc", 1);
}

if(!defined("cmp_indexdesc")) {
function cmp_indexdesc($a, $b) {
global $sapi_obj;
$index = $sapi_obj->env["index"];
if($index=='ID')
return ($a[$index] > $b[$index]) ? 1 : -1;
else if ($index=='DATE'){
$date_a=explode('/',$a[$index]);
$date_b=explode('/',$b[$index]);
$a_index=mktime (0,0,0, $date_a[1],$date_a[0], $date_a[2]);
$b_index=mktime (0,0,0, $date_b[1], $date_b[0], $date_b[2]);
return strcmp($b_index,$a_index);
}
else
return strcmp($b[$index],$a[$index]);
}
define("cmp_indexdesc", 1);
}
Download: common_extfunctions.inc.zip
For verion: Sapid 1.2.3 RC3

If someone will use it, please, tell me about results in comments.

1 Comments:

At 11:07 PM, Blogger Henk said...

Dear Vapel,

I tried the common_extfunctions.inc.php that you provided here. Good work; finally, sorting on ID is partially working. :) The sorting on DATE is not yet working. :(
Also, the ASC and DESC are reversed.
ASC now shows 50, 49, 48, 47...
DESC now shows 1, 2, 3, 4...
The definition of ascending is that it is going up in value; like 1, 2, 3...
The definition of descending is that it is going down in value (the opposite of ascending); like 3, 2, 1.

Hope you can improve things with this comment.

Regards,
Henk

 

Post a Comment

<< Home