Matthew B
asked on
Most effecient way to Sort an Array multiple times
What is the most efficient way to sort an array multiple times?
I have a leaderboard that lists clients activity in descending order for specific time periods.
Periods: Today, This Week, This Month, This Year, All Time
Currently im a using a script in my controller that will go over my array and put it in desc order based on a single column. Is running this script 5 times the only way to resort the data for each new category so they are all in descending order?
My controller (found this script online):
My data looks like this.
I have a leaderboard that lists clients activity in descending order for specific time periods.
Periods: Today, This Week, This Month, This Year, All Time
Currently im a using a script in my controller that will go over my array and put it in desc order based on a single column. Is running this script 5 times the only way to resort the data for each new category so they are all in descending order?
My controller (found this script online):
function make_comparer() {
// Normalize criteria up front so that the comparer finds everything tidy
$criteria = func_get_args();
foreach ($criteria as $index => $criterion) {
$criteria[$index] = is_array($criterion)
? array_pad($criterion, 3, null)
: array($criterion, SORT_ASC, null);
}
return function($first, $second) use ($criteria) {
foreach ($criteria as $criterion) {
// How will we compare this round?
list($column, $sortOrder, $projection) = $criterion;
$sortOrder = $sortOrder === SORT_DESC ? -1 : 1;
// If a projection was defined project the values now
if ($projection) {
$lhs = call_user_func($projection, $first[$column]);
$rhs = call_user_func($projection, $second[$column]);
}
else {
$lhs = $first[$column];
$rhs = $second[$column];
}
// Do the actual comparison; do not return if equal
if ($lhs < $rhs) {
return -1 * $sortOrder;
}
else if ($lhs > $rhs) {
return 1 * $sortOrder;
}
}
return 0; // tiebreakers exhausted, so $first == $second
};
}
uasort($arrV, make_comparer(['Today', SORT_DESC]));
My data looks like this.
0 => {#863 ▼
+"client": "Client 1"
+"today": "0"
+"past 7 days": "1"
+"past 30 days": "2"
+"this year": "3"
+"all time": "12"
+"balanceType": "Checking"
}
1 => {#864 ▼
+"client": "Client 1"
+"today": "0"
+"past 7 days": "0"
+"past 30 days": "0"
+"this year": "8"
+"all time": "7"
+"balanceType": "Savings"
}
2 => {#865 ▼
+"client": "Client 2"
+"today": "0"
+"past 7 days": "0"
+"past 30 days": "6"
+"this year": "85"
+"all time": "756"
+"balanceType": "Checking"
}
3 => {#866 ▼
+"client": "Client 2"
+"today": "0"
+"past 7 days": "0"
+"past 30 days": "66"
+"this year": "100"
+"all time": "0"
+"balanceType": "Savings"
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.