note 66188 added to function.usort
| From: | ("martin#classaxecom<>") | Date: | Tue, 16 May 2006 20:07:03 +0000 |
| Subject: | note 66188 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-111406@lists.php.net to get a copy of this message | ||
Refinement of arfsort to allow per-field sort direction setting:
<?
function arfsort( $a, $fl ){
$GLOBALS['__ARFSORT_LIST__'] = $fl;
usort( $a, 'arfsort_func' );
return $a;
}
// extended to allow sort direction per field sorted against
function arfsort_func( $a, $b ){
foreach( $GLOBALS['__ARFSORT_LIST__'] as $f ) {
switch ($f[1]) { // switch on ascending or descending value
case "d":
$strc = strcmp( strtolower($b[$f[0]]), strtolower($a[$f[0]]) );
if ( $strc != 0 ){
return $strc;
}
break;
default:
$strc = strcmp( strtolower($a[$f[0]]), strtolower($b[$f[0]]) );
if ( $strc != 0 ){
return $strc;
}
break;
}
}
return 0;
}
// Just prints out record contents
function show($test) {
foreach ($test as $key=>$row) {
print "<li>($key) ".$row['fruit']." is
".$row['type']." at ".$row['time']." on
".$row['date']."</li>\n";
}
print "<hr>";
}
// Example usage
$test = array(
array( 'fruit' => 'Lemon', 'type' => 'sour',
'date' => '2006-05-16', 'time' => '12:36'),
array( 'fruit' => 'Banana','type' =>
'sweet','date' => '2006-05-17','time' =>
'12:35'),
array( 'fruit' => 'Apple', 'type' =>
'sweet','date' => '2006-05-17','time' =>
'12:35'),
array( 'fruit' => 'green apple', 'type' => 'sour',
'date' => '2006-05-16', 'time' => '12:37')
);
show($test);
$order_arr =
array(
array('date','d'), // d means decending - swap for 'a' to see
effect
array('time','a'),
array('fruit','a')
);
$sorted = arfsort( $test, $order_arr);
show($sorted);
?>
----
Server IP: 66.163.161.117
Probable Submitter: 67.70.123.25
----
X-Spam-Status: No, hits=3.3 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER,
HTML_MESSAGE autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- http://master.php.net/note/edit/66188
Del: integrated -- http://master.php.net/note/delete/66188/integrated
Del: useless -- http://master.php.net/note/delete/66188/useless
Del: bad code -- http://master.php.net/note/delete/66188/bad+code
Del: spam -- http://master.php.net/note/delete/66188/spam
Del: non-english -- http://master.php.net/note/delete/66188/non-english
Del: in docs -- http://master.php.net/note/delete/66188/in+docs
Del: other reasons-- http://master.php.net/note/delete/66188
Reject -- http://master.php.net/note/reject/66188
Search -- http://master.php.net/manage/user-notes.php