I have a largish table of data pulled from my database (~1500 rows, each with 10-15 fields) and I'm doing a number of filters and generating some stats and storing these in an excel spreadsheet for the user to download.
Rather than hit the database with the same fairly-complicated query over and over with only minor modifications (to the WHERE and ORDER BY), I'm doing one trip to the DB, putting the results into one big array and then using array_filter
and array_multisort
to get my new views of the data.
I'm new to array_multisort
so I'll post what I've done here for critique.
// an numerical array of associative arrays
$records = $dbResult->convertToArray();
$fields = $dbResult->getFieldNames();
// this is run once at the start
$sortArr = array();
foreach ($fields as $field) $sortArr[$field] = array();
foreach ($records as $r) {
foreach ($r as $key => $value) {
$sortArr[$key][] = $value;
}
}
// and then to sort:
array_multisort(
$sortArr['Date Completed'], SORT_DESC,
$sortArr['Last Name'], SORT_ASC,
$sortArr['First Name'], SORT_ASC,
$sortArr['Course'], SORT_ASC,
$records
);
This works fine, though the initial "copy the entire result into another array" seems strange to me. The problem occurs when I need to sort the list again. I have the feeling that my $sortArr
needs to stay in sync with the $records
array, but that it gets broken after each sort.
I'm not even sure that this is the intended use of array_multisort
, so I might be way off track here. Can anyone give some advice or tips? How do you sort multidimensional arrays?