Came up with the following function to perform an array sort, making use of closures to define the callback function that will be used by usort(). Trying to decide if it's a decent way to accomplish this, or if there might be a cleaner way?
/**
* Sort the array of reviews
* @return array
* @param array $data
* @param string $orderBy
*/
private function applySort(array $data, $orderBy)
{
switch($orderBy) {
case 'mosthelpful':
$sortFunc = function($a, $b) {
$diff = strtotime($b['likes']) - strtotime($a['likes']);
return ($diff != 0) ? $diff :
strtotime($b['review_timestamp']) - strtotime($a['review_timestamp']);
};
break;
case 'leasthelpful':
$sortFunc = function($a, $b) {
$diff = strtotime($b['dislikes']) - strtotime($a['dislikes']);
return ($diff != 0) ? $diff :
strtotime($b['review_timestamp']) - strtotime($a['review_timestamp']);
};
break;
case 'oldtonew':
$sortFunc = function($a, $b) {
return strtotime($a['review_timestamp']) - strtotime($b['review_timestamp']);
};
break;
case 'newtoold':
default:
$sortFunc = function($a, $b) {
return strtotime($b['review_timestamp']) - strtotime($a['review_timestamp']);
};
}
usort($data, $sortFunc);
return $data;
}