views:

333

answers:

1

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?

+1  A: 

Here's what I ended up going with. It's a slightly modified version of a function posted by martin in the comments on the usort page in the PHP manual.

function arfsort( &$array, $fieldList ){
    if (!is_array($fieldList)) {
        $fieldList = array(array($fieldList, SORT_ASC));
    } else {
        for ($i = 0; $i < count($fieldList); ++$i) {
            if (is_array($fieldList[$i])) {
                if (!isset($fieldList[$i][1])) $fieldList[$i][1] = SORT_ASC;
            } else {
                $fieldList[$i] = array($fieldList[$i], SORT_ASC);
            }
        }
    }
    $GLOBALS['__ARFSORT_LIST__'] = $fieldList;
    usort( $array, 'arfsort_func' );

}

function arfsort_func( $a, $b ){
    foreach( $GLOBALS['__ARFSORT_LIST__'] as $f ) {
        $strc = strcasecmp($b[$f[0]], $a[$f[0]]);
        if ( $strc != 0 ){
            return $strc * (!empty($f[1]) && $f[1] == SORT_DESC ? 1 : -1);
        }
    }
    return 0;
}

I've hopefully made the function a little more robust than the original solution. Usage:

arfsort($my2DArray, "id");  // just sort by the id field, ascending
// sort by these lastName then firstName, ascending
arfsort($my2DArray, array("lastName", "firstName"));

arfsort($my2DArray, array(
    array("date", SORT_DESC),    // sort by date DESC
    array("lastName", SORT_ASC), // then by last name ascending
    array("firstName"),          // SORT_ASC is the default
    "middleInitial"              // and you don't need to wrap stuff in an array.
));
nickf