"PHP 다중정렬 sortOrderBy()"의 두 판 사이의 차이

잔글 (봇: 자동으로 텍스트 교체 (-== 참고 자료 == +==참고==))
잔글 (Jmnote님이 PHP 다중정렬 sortValues() 문서를 PHP 다중정렬 sortOrderBy() 문서로 이동했습니다)
 
(사용자 2명의 중간 판 14개는 보이지 않습니다)
1번째 줄: 1번째 줄:
;PHP orderBy()


==orderBy.php 작성==
==개요==
<source lang='php'>
;PHP 다중정렬 orderBy()
<?php
;PHP 다중정렬 sortValues()
function orderBy(&$ary, $clause, $ascending = true) {
;PHP 다중정렬 sortOrderBy()
$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();
<syntaxhighlight lang='php' line run>
$dirAry = array();
function sortValues($array, $by, $ascending=[]) {
foreach($keys as $key) {  
    $makeComparer = function ($criteria) {
$key = explode(' ', trim($key));
        return function ($a, $b) use ($criteria) {
$keyAry[] = trim($key[0]);  
            foreach( $criteria[0] as $i => $key) {
if(isset($key[1])) {
                $asc = $criteria[1][$i] ?? true;
$dir = strtolower(trim($key[1]));  
                if ($a[$key] < $b[$key]) return $asc ? -1 : 1;
$dirAry[] = $dirMap[$dir] ? $dirMap[$dir] : $def;  
                if ($a[$key] > $b[$key]) return $asc ? 1 : -1;
} else {
            }
$dirAry[] = $def;  
            return 0;
}
        };
}  
    };
    usort($array, $makeComparer([$by, $ascending]));
    return $array;
}


$fnBody = '';
$employees = [
for($i = count($keyAry) - 1; $i >= 0; $i--) {
['EmployeeID'=>'1', 'Name'=>'한놈', 'BirthDate'=>'1999-01-01'],
$k = $keyAry[$i];
['EmployeeID'=>'2', 'Name'=>'두시기', 'BirthDate'=>'2000-01-01'],
$t = $dirAry[$i];
['EmployeeID'=>'3', 'Name'=>'석삼', 'BirthDate'=>'1999-01-01'],
$f = -1 * $t;
['EmployeeID'=>'4', 'Name'=>'너구리', 'BirthDate'=>'2000-01-01'],
$aStr = '$a[\''.$k.'\']';
];
$bStr = '$b[\''.$k.'\']';
if(strpos($k, '(') !== false) {
$aStr = '$a->'.$k;
$bStr = '$b->'.$k;  
}


if($fnBody == '') {
# BirthDate 오름차순
$fnBody .= "if({$aStr} == {$bStr}) { return 0; }\n";  
$employees1 = sortValues($employees, ['BirthDate']);
$fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n";               
# BirthDate 내림차순
} else {
$employees2 = sortValues($employees, ['BirthDate'], [false]);
$fnBody = "if({$aStr} == {$bStr}) {\n" . $fnBody;  
# BirthDate, Name 오름차순
$fnBody .= "}\n";
$employees3 = sortValues($employees, ['BirthDate','Name']);
$fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n";
# BirthDate 오름차순, Name 내림차순
}
$employees4 = sortValues($employees, ['BirthDate','Name'], [true,false]);
}


if($fnBody) {  
# 출력
$sortFn = create_function('$a,$b', $fnBody);
for($i=1; $i<=4; $i++) {
usort($ary, $sortFn);      
    $var = "employees$i";
}
    echo "$var: \n", str_replace('},',"},\n",json_encode($$var,JSON_UNESCAPED_UNICODE))."\n\n";
}
}
</source>
</syntaxhighlight>
 
==orderBy_test.php 작성==
<source lang='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);
</source>
:→ 생년월일(BirthDate) 역순 정렬, 이름순 정렬
 
==테스트==
<source lang='console'>
[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
        )
 
)
</source>


==같이 보기==
==같이 보기==
*[[PHPLinq 2차원 배열 employees 예제]]
* [[PHPLinq 2차원 배열 employees 예제]]
*[[PHPLinq 2차원 배열 employees 예제 2]]
* [[PHPLinq 2차원 배열 employees 예제 2]]
*[[PHPLinq 설치]]
* [[PHPLinq 설치]]
* [[함수 orderBy()]]


==참고==
==참고==
*http://php.net/manual/en/function.usort.php
*http://php.net/manual/en/function.usort.php


[[분류: PHP]]
[[분류: PHP 정렬]]
[[분류: 정렬]]

2021년 10월 2일 (토) 16:28 기준 최신판

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 }}