PHP Velho Oeste 2024

uasort

(PHP 4, PHP 5, PHP 7)

uasort사용자 정의 비교 함수로 배열을 정렬하고 인덱스 연관성을 유지

설명

bool uasort ( array &$array , callback $cmp_function )

이 함수는 배열 인덱스가 그와 관련되어 있는 배열 원소들과의 연관성을 유지하면서 사용자 정의 비교 함수를 사용하여 배열을 정렬한다.

연관 배열을 정렬하면서 실제 원소 순서가 중요할 때 주로 사용합니다.

인수

array

입력 배열.

cmp_function

사용자 정의 비교 함수의 예제는 usort()uksort()를 참고하십시오.

반환값

성공 시 TRUE를, 실패 시 FALSE를 반환합니다.

참고

  • usort() - 사용자 정의 비교 함수를 사용하여 값에 의한 배열 정렬
  • uksort() - 사용자 정의 비교 함수를 사용하여 키에 의한 배열 정렬
  • asort() - 배열을 정렬하고 인덱스 상관 관계를 유지
  • arsort() - 배열을 내림차순 정렬하고 인덱스의 상관관계를 유지
  • ksort() - 키에 의한 배열 정렬
  • rsort() - 역순으로 배열 정렬
  • sort() - 배열 정렬

add a note add a note

User Contributed Notes 3 notes

up
153
magikMaker
13 years ago
a quick reminder on the syntax if you want to use uasort in a Class or Object:

<?php

// procedural:
uasort($collection, 'my_sort_function');

// Object Oriented
uasort($collection, array($this, 'mySortMethod'));

// Objet Oriented with static method
uasort($collection, array('self', 'myStaticSortMethod'));

?>
up
32
yannick dot battail at gmail dot com
13 years ago
An Example using anonymous function.
Anonymous functions make some time the code easier to understand.
<?php
$fruits
= array('Orange9','Orange11','Orange10','Orange6','Orange15');
uasort ( $fruits , function ($a, $b) {
            return
strnatcmp($a,$b); // or other function/code
       
}
    );
print_r($fruits);
?>
returns
Array
(
    [3] => Orange6
    [0] => Orange9
    [2] => Orange10
    [1] => Orange11
    [4] => Orange15
)
up
2
php at eden2 dot com
20 years ago
Is it just me, or are the examples below misleading, and actually demonstrating situations that would be more appropriate for usort()?

After trying to make sense of the uasort() description, it sounds like it's more for sorting a 1D array like this:

"john" => "$23.12"
"tim" => "$6.50"
"bob" => "$18.54"

and getting back:

"tim" => "$6.50"
"bob" => "$18.54"
"john" => $23.12"

(assuming, of course, that your sort function is lopping off the $ and evaluating as a number -- which would complicate the use of asort() ;)
To Top