PHP 다중정렬 sortOrderBy()

Jmnote (토론 | 기여)님의 2015년 6월 23일 (화) 17:48 판 (Jmnote 사용자가 PHP orderBy() 문서를 PHP 함수 orderBy() 문서로 옮겼습니다)
PHP orderBy()

1 orderBy.php 작성

<?php
function orderBy(&$ary, $clause, $ascending = true) { 
	$clause = str_ireplace('order by', '', $clause); 
	$clause = preg_replace('/\s+/', ' ', $clause); 
	$keys = explode(',', $clause); 
	$dirMap = array('desc' => 1, 'asc' => -1); 
	$def = $ascending ? -1 : 1; 

	$keyAry = array(); 
	$dirAry = array(); 
	foreach($keys as $key) { 
		$key = explode(' ', trim($key)); 
		$keyAry[] = trim($key[0]); 
		if(isset($key[1])) { 
			$dir = strtolower(trim($key[1])); 
			$dirAry[] = $dirMap[$dir] ? $dirMap[$dir] : $def; 
		} else { 
			$dirAry[] = $def; 
		} 
	} 

	$fnBody = ''; 
	for($i = count($keyAry) - 1; $i >= 0; $i--) { 
		$k = $keyAry[$i]; 
		$t = $dirAry[$i]; 
		$f = -1 * $t; 
		$aStr = '$a[\''.$k.'\']'; 
		$bStr = '$b[\''.$k.'\']'; 
		if(strpos($k, '(') !== false) { 
			$aStr = '$a->'.$k; 
			$bStr = '$b->'.$k; 
		} 

		if($fnBody == '') { 
			$fnBody .= "if({$aStr} == {$bStr}) { return 0; }\n"; 
			$fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n";                
		} else { 
			$fnBody = "if({$aStr} == {$bStr}) {\n" . $fnBody; 
			$fnBody .= "}\n"; 
			$fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n"; 
		} 
	} 

	if($fnBody) { 
		$sortFn = create_function('$a,$b', $fnBody); 
		usort($ary, $sortFn);        
	} 
}

2 orderBy_test.php 작성

<?php
include 'orderBy.php';

$employees = array(
  array('EmployeeID'=>'1', 'Name'=>'한놈', 'BirthDate'=>'1999-01-01'),
  array('EmployeeID'=>'2', 'Name'=>'두시기', 'BirthDate'=>'2000-01-01'),
  array('EmployeeID'=>'3', 'Name'=>'석삼', 'BirthDate'=>'1999-01-01'),
  array('EmployeeID'=>'4', 'Name'=>'너구리', 'BirthDate'=>'2000-01-01')
);
orderBy($employees, 'BirthDate DESC, Name ASC');
print_r($employees);
→ 생년월일(BirthDate) 역순 정렬, 이름순 정렬

3 테스트

[root@zetawiki ~]# php orderBy_test.php 
Array
(
    [0] => Array
        (
            [EmployeeID] => 4
            [Name] => 너구리
            [BirthDate] => 2000-01-01
        )

    [1] => Array
        (
            [EmployeeID] => 2
            [Name] => 두시기
            [BirthDate] => 2000-01-01
        )

    [2] => Array
        (
            [EmployeeID] => 3
            [Name] => 석삼
            [BirthDate] => 1999-01-01
        )

    [3] => Array
        (
            [EmployeeID] => 1
            [Name] => 한놈
            [BirthDate] => 1999-01-01
        )

)

4 같이 보기

5 참고 자료

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