Multisort by key

Standard

In some situations you want to organize your arrays numerically, or by a date that is in your array on a given value. This method takes in an array, attempts to sort it in the direction specified based on the field parameter (depth 1) designated. If the field you are passing in is a date, it can also formatted and arrange.

I used this particular method for organizing names based on a given rating, then by date of birth.

Usage:

$data = array(
            'Justin' => array('Points' => 5),
            'Thomas' => array('Points' => 1),
            'Adam' => array('Points' => 10)
        );

$result = $this->multiSort($data, “SORT_DESC”, “Points”, false);
print_r($result);

 

Note: additional depths can be specified by changing “Points” to “Points/Depth3Field” and so on…

Result:

array(
	'Adam' => array('Points' => 10),
	'Justin' => array('Points' => 5),
	'Thomas' => array('Points' => 1)
)

Method:

/**
 * Private multiSort
 *
 * @array() $data
 * @var $sortDirection
 * @var $field
 * @bool $isDate
 * @return $data (sorted)
 */
private function multiSort($data, $sortDirection, $field, $isDate) {
    if (empty($data) || !is_array($data) || count($data) < 2) {
        return $data;
    }

    $parts = explode("/", $field);
    foreach ($data as $key => $row) {
        $temp = &$row;
        foreach ($parts as $key2) {
            $temp = &$temp[$key2];
        }
        $orderByDate[$key] = ($isDate ? strtotime($temp) : $temp);
    }
    unset($temp);
    unset($parts);

    if ($sortDirection == "SORT_DESC") {
        array_multisort($orderByDate, SORT_DESC, $data);
    } else {
        array_multisort($orderByDate, SORT_ASC, $data);
    }
    unset($orderByDate);
    return $data;
}