/*******************************************************************
* This function sort a multi dimensional array by key, order, type.
*
* @param array &$data referenz of a multi dimensional array
* @param string $keys sort by key name
* @param string $order order type (ASC|DESC)
* @param integer $type compare type (0..4)
* @return void
*******************************************************************/
function msort ( &$data, $keys = 0, $order = "ASC", $type = 0 ) {
// Get the compare type
switch($type) {
case 1: // Case insensitive natural
$compare = 'strcasenatcmp'; break;
case 2: // Case sensitive natural
$compare = 'strnatcmp'; break;
case 3: // Case sensitive string
$compare = 'strcmp'; break;
case 4: // Case insensitive string
$compare = 'strcasecmp'; break;
default: // Default: Numeric
$compare = Null; break;
}
// Get the order type (ASC|DESC)
if ( $order == "DESC" ) { // DESC: >
if ( isset($compare) )
(string) $body = $compare.'( $b['.$keys.'], $a['.$keys.'] )';
else
(string) $body = '$b['.$keys.'] - $a['.$keys.']';
} else { // ASC: <
if ( isset($compare) )
(string) $body = $compare.'( $a['.$keys.'], $b['.$keys.'] )';
else
(string) $body = '$a['.$keys.'] - $b['.$keys.']';
}
// Sort the array data by a defined user function
uasort( $data, create_function( '$a, $b', 'return ('.$body.');' ) );
}
// @example
$arr = array ( 10 => array('id' => 'dix', 'aa' => '1010'),
100 => array('id' => 'cent', 'aa' => '100100'),
2 => array('id' => 'deux', 'aa' => '22'),
7 => array('id' => 'sept', 'aa' => '77'));
header( 'Content-Type: text/plain' );
print_r( msort( $arr, 'id', 'ASC', 3 ) );