Tuesday, December 29, 2009

PHP: sort an array with a user-defined comparison function

This is the way to sort an array with the user-defined function

$a = array(
'Alex'=>array('age'=>22,'hoby'=>'basketball'),
'John'=>array('age'=>21,'hoby'=>'soccer'),
'Ivan'=>array('age'=>30,'hoby'=>'vodka'),
);
// creating user-defined function
$newF = create_function('$item1,$item2',
'return ($item1["age"]<$item2["age"])?true:false;');

usort($a,$newF);
var_dump($a);

No comments:

Post a Comment

 
Software