PHP 다중정렬 sortOrderBy()

1 개요[ | ]

PHP 다중정렬 orderBy()
PHP 다중정렬 sortValues()
PHP 다중정렬 sortOrderBy()
function sortValues($array, $by, $ascending=[]) {
    $makeComparer = function ($criteria) {
        return function ($a, $b) use ($criteria) {
            foreach( $criteria[0] as $i => $key) {
                $asc = $criteria[1][$i] ?? true;
                if ($a[$key] < $b[$key]) return $asc ? -1 : 1;
                if ($a[$key] > $b[$key]) return $asc ? 1 : -1;
            }
            return 0;
        };
    };
    usort($array, $makeComparer([$by, $ascending]));
    return $array;
}

$employees = [
	['EmployeeID'=>'1', 'Name'=>'한놈', 'BirthDate'=>'1999-01-01'],
	['EmployeeID'=>'2', 'Name'=>'두시기', 'BirthDate'=>'2000-01-01'],
	['EmployeeID'=>'3', 'Name'=>'석삼', 'BirthDate'=>'1999-01-01'],
	['EmployeeID'=>'4', 'Name'=>'너구리', 'BirthDate'=>'2000-01-01'],
];

# BirthDate 오름차순
$employees1 = sortValues($employees, ['BirthDate']);
# BirthDate 내림차순
$employees2 = sortValues($employees, ['BirthDate'], [false]);
# BirthDate, Name 오름차순
$employees3 = sortValues($employees, ['BirthDate','Name']);
# BirthDate 오름차순, Name 내림차순
$employees4 = sortValues($employees, ['BirthDate','Name'], [true,false]);

# 출력
for($i=1; $i<=4; $i++) {
    $var = "employees$i";
    echo "$var: \n", str_replace('},',"},\n",json_encode($$var,JSON_UNESCAPED_UNICODE))."\n\n";
}

2 같이 보기[ | ]

3 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}