note 66188 deleted from function.usort by danbrown

From: Date: Sun, 23 Jan 2011 16:26:54 +0000
Subject: note 66188 deleted from function.usort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176069@lists.php.net to get a copy of this message
Note Submitter: martin # classaxe com <>< ---- Refinement of arfsort to allow per-field sort direction setting: <?php 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); ?>

« previous php.notes (#176069) next »