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

3번째 줄: 3번째 줄:


<syntaxhighlight lang='php' line run>
<syntaxhighlight lang='php' line run>
function orderBy(&$ary, $clause, $ascending = true) {  
<?php
$clause = str_ireplace('order by', '', $clause);
function sortValues($array, $by, $ascending=[]) {
$clause = preg_replace('/\s+/', ' ', $clause);
    $makeComparer = function ($criteria) {
$keys = explode(',', $clause);
        $comparer = function ($a, $b) use ($criteria) {
$dirMap = array('desc' => 1, 'asc' => -1);
            for($i=0; $i<count($criteria[0]); $i++) {
$def = $ascending ? -1 : 1;  
                $key = $criteria[0][$i];
 
                $asc = $criteria[1][$i] ?? true;
$keyAry = array();
                if ($a[$key] < $b[$key]) return $asc ? -1 : 1;
$dirAry = array();  
                if ($a[$key] > $b[$key]) return $asc ? 1 : -1;
foreach($keys as $key) {  
            }
$key = explode(' ', trim($key));
            return 0;
$keyAry[] = trim($key[0]);  
        };
if(isset($key[1])) {
        return $comparer;
$dir = strtolower(trim($key[1]));
    };
$dirAry[] = $dirMap[$dir] ? $dirMap[$dir] : $def;  
    $comparer = $makeComparer([$by, $ascending]);
} else {
    usort($array, $comparer);
$dirAry[] = $def;
    return $array;
}
}
 
$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);      
}
}
}


57번째 줄: 28번째 줄:
['EmployeeID'=>'4', 'Name'=>'너구리', 'BirthDate'=>'2000-01-01'],
['EmployeeID'=>'4', 'Name'=>'너구리', 'BirthDate'=>'2000-01-01'],
];
];
orderBy($employees, 'BirthDate DESC, Name ASC');
 
print_r($employees);
# BirthDate 오름차순
$employees = sortValues($employees, ['BirthDate']);
echo preg_replace('/\\},/',"},\n",json_encode($employees,JSON_UNESCAPED_UNICODE))."\n\n";
 
# BirthDate 내림차순
$employees = sortValues($employees, ['BirthDate'],[false]);
echo preg_replace('/\\},/',"},\n",json_encode($employees,JSON_UNESCAPED_UNICODE))."\n\n";
 
# BirthDate, Name 오름차순
$employees = sortValues($employees, ['BirthDate','Name']);
echo preg_replace('/\\},/',"},\n",json_encode($employees,JSON_UNESCAPED_UNICODE))."\n\n";
 
# BirthDate 오름차순, Name 내림차순
$employees = sortValues($employees, ['BirthDate','Name'], [true,false]);
echo preg_replace('/\\},/',"},\n",json_encode($employees,JSON_UNESCAPED_UNICODE))."\n\n";
</syntaxhighlight>
</syntaxhighlight>
:→ 생년월일(BirthDate) 역순 정렬, 이름순 정렬


==같이 보기==
==같이 보기==

2021년 10월 2일 (토) 14:55 판

1 개요

PHP orderBy()
<?php
function sortValues($array, $by, $ascending=[]) {
    $makeComparer = function ($criteria) {
        $comparer = function ($a, $b) use ($criteria) {
            for($i=0; $i<count($criteria[0]); $i++) {
                $key = $criteria[0][$i];
                $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;
        };
        return $comparer;
    };
    $comparer = $makeComparer([$by, $ascending]);
    usort($array, $comparer);
    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 오름차순
$employees = sortValues($employees, ['BirthDate']);
echo preg_replace('/\\},/',"},\n",json_encode($employees,JSON_UNESCAPED_UNICODE))."\n\n";

# BirthDate 내림차순
$employees = sortValues($employees, ['BirthDate'],[false]);
echo preg_replace('/\\},/',"},\n",json_encode($employees,JSON_UNESCAPED_UNICODE))."\n\n";

# BirthDate, Name 오름차순
$employees = sortValues($employees, ['BirthDate','Name']);
echo preg_replace('/\\},/',"},\n",json_encode($employees,JSON_UNESCAPED_UNICODE))."\n\n";

# BirthDate 오름차순, Name 내림차순
$employees = sortValues($employees, ['BirthDate','Name'], [true,false]);
echo preg_replace('/\\},/',"},\n",json_encode($employees,JSON_UNESCAPED_UNICODE))."\n\n";

2 같이 보기

3 참고

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