How to sort getrecords result when the same table is joined twice

3 posts by 2 authors in: Forums > CMS Builder
Last Post: June 17, 2017   (RSS)

By kitsguru - June 15, 2017

Working through the above example I created a function that I can use:

**
 * sortRecordsbyCategory
 *
 *
 * usage : use after call to getrecords
 *         pass the array of found records and up to fields to sort
 *         only needs to be used when the same table is joined
 *         with 2 or more columns
 *
 * $linkRecords = ($linkRecords, 'category:label');
 * $linkRecords = ($linkRecords, 'sub_category:label');
 * $linkRecords = ($linkRecords, 'category:label', 'sub_category:label');
 * $linkRecords = ($linkRecords, 'sub_category:label', 'category:label');
 *
 * @param  array $records  to be sorted
 * @param  string $field1 first field to use for sort
 * @param  string $field2 second field to use for sort
 * @return array - sorted
 */
function sortRecordsByCategory($records, $field1, $field2 = "title")
{
    // build variables to sort the array
    //
    foreach ($records as $key => $row) {
        $f1[$key]  = $row[$field1];
        $f2[$key]  = $row[$field2];
    }
    array_multisort($f1, SORT_ASC, $f2, SORT_ASC, $records);

    return $records;
}

Jeff Shields

By Dave - June 17, 2017 - edited: June 17, 2017

Nice!  Thanks for sharing!  I always found array_multisort particularly confusing. ;-)

Dave Edis - Senior Developer
interactivetools.com