매일 PHP 프로그래밍에서는 종종 문자열 배열을 정렬해야하지만 기본 사전 정렬 ( 정렬 , USORT 등)은 숫자로 문자열을 잘 처리하지 않습니다. 예를 들어, img1.png , img2.png , img10.png 와 같은 파일 이름이 일반 문자열과 비교되면 분류 결과는 img1.png , img10.png , img2.png 가되며, 이는 분명히 인간의 자연 분류 습관과 일치하지 않습니다.
"자연 분류"를 달성하기 위해 PHP는 각각 대사자 민감성 및 사례에 비해 자연적인 자연 분류에 해당하는 Strnatcmp 및 Strnatcasecmp 함수를 제공합니다.
또한 배열을 정렬하면 모든 소문자를 돌리거나 불필요한 공간을 제거하는 등 배열의 각 요소를 균일하게 포맷해야합니다. 현재 Array_Map을 사용하여 달성 할 수 있습니다.
이 기사는이 두 도구를 결합하여 배열의 문자열을 균일하게 포맷 한 다음 자연스럽게 정렬하는 방법을 소개합니다.
1 ??? 데이터 배열 준비 <br> 예를 들어 파일 이름 세트를 작성하겠습니다.
$files = ['Img10.png', 'img2.png', 'IMG1.png', 'img20.png', 'img11.png'];
2 ?? array_map <br>을 사용한 형식 요소 우리 모두를 소문자로 변환하고 싶다고 가정합니다.
$formattedFiles = array_map('strtolower', $files);
더 복잡한 것들 (예 : de-spaces 및 unified 확장)을 처리하려면 익명 기능을 작성할 수 있습니다.
$formattedFiles = array_map(function($item) {
return strtolower(trim($item));
}, $files);
3 ???? 사용자 정의 분류 기능
PHP의 USORT는 사용자 정의 기능으로 정렬 할 수 있습니다.
usort($formattedFiles, 'strnatcasecmp');
참고 : strnatcasecmp는 정렬에 직접 사용되는 함수가 아닌 비교 함수입니다.
<?php
$files = ['Img10.png', 'img2.png', 'IMG1.png', 'img20.png', 'img11.png'];
// 첫 번째 단계:통합 형식(소문자를 돌립니다 + 공간을 제거하십시오)
$formattedFiles = array_map(function($item) {
return strtolower(trim($item));
}, $files);
// 2 단계:자연 분류(케이스 둔감)
usort($formattedFiles, 'strnatcasecmp');
// 출력 결과
foreach ($formattedFiles as $file) {
echo $file . "\n";
}
?>
실행 결과 :
img1.png
img2.png
img10.png
img11.png
img20.png
우리가 일련의 URL을 다루고 있다고 가정합니다.
$urls = [
'https://gitbox.net/File10.html',
'https://gitbox.net/file2.html',
'https://gitbox.net/FILE1.html',
'https://gitbox.net/file20.html',
'https://gitbox.net/file11.html',
];
파일 이름으로 정렬하고 파일 이름을 먼저 추출한 다음 정렬 할 수 있습니다.
<?php
$urls = [
'https://gitbox.net/File10.html',
'https://gitbox.net/file2.html',
'https://gitbox.net/FILE1.html',
'https://gitbox.net/file20.html',
'https://gitbox.net/file11.html',
];
// 파일 이름 부분을 추출하고 바인딩하십시오 URL
$mapped = array_map(function($url) {
$parts = parse_url($url);
$file = basename($parts['path']);
return ['url' => $url, 'file' => strtolower($file)];
}, $urls);
// 按文件名자연 분류
usort($mapped, function($a, $b) {
return strnatcasecmp($a['file'], $b['file']);
});
// 출력 정렬 URL
foreach ($mapped as $item) {
echo $item['url'] . "\n";
}
?>
산출:
https://gitbox.net/FILE1.html
https://gitbox.net/file2.html
https://gitbox.net/File10.html
https://gitbox.net/file11.html
https://gitbox.net/file20.html