라이브러리

[PHP] CollectionRemove::sort - 정렬 기준 설정




PHP의 CollectionRemove::sort는 컬렉션 내의 요소를 정렬하는 메서드입니다. 이 메서드는 컬렉션 내의 요소를 오름차순 또는 내림차순으로 정렬할 수 있습니다.

사용법


CollectionRemove::sort 메서드는 다음과 같이 사용할 수 있습니다.

#hostingforum.kr
php

use SpatieCollectionRemoveCollectionRemove;



$collection = [

    ['name' => 'John', 'age' => 25],

    ['name' => 'Alice', 'age' => 30],

    ['name' => 'Bob', 'age' => 20],

];



$sortedCollection = CollectionRemove::sort($collection, 'age', 'asc');



print_r($sortedCollection);



결과


#hostingforum.kr
php

Array

(

    [0] => Array

        (

            [name] => Bob

            [age] => 20

        )



    [1] => Array

        (

            [name] => John

            [age] => 25

        )



    [2] => Array

        (

            [name] => Alice

            [age] => 30

        )



)



옵션


CollectionRemove::sort 메서드는 두 개의 옵션을 제공합니다.

* `sort`: 정렬할 컬렉션의 요소를 정렬하는 방법을 지정합니다. `asc` 또는 `desc`를 지정할 수 있습니다.
* `key`: 정렬할 컬렉션의 요소의 키를 지정합니다.

예제


# 오름차순 정렬


#hostingforum.kr
php

use SpatieCollectionRemoveCollectionRemove;



$collection = [

    ['name' => 'John', 'age' => 25],

    ['name' => 'Alice', 'age' => 30],

    ['name' => 'Bob', 'age' => 20],

];



$sortedCollection = CollectionRemove::sort($collection, 'age', 'asc');



print_r($sortedCollection);



# 내림차순 정렬


#hostingforum.kr
php

use SpatieCollectionRemoveCollectionRemove;



$collection = [

    ['name' => 'John', 'age' => 25],

    ['name' => 'Alice', 'age' => 30],

    ['name' => 'Bob', 'age' => 20],

];



$sortedCollection = CollectionRemove::sort($collection, 'age', 'desc');



print_r($sortedCollection);



# 이름으로 정렬


#hostingforum.kr
php

use SpatieCollectionRemoveCollectionRemove;



$collection = [

    ['name' => 'John', 'age' => 25],

    ['name' => 'Alice', 'age' => 30],

    ['name' => 'Bob', 'age' => 20],

];



$sortedCollection = CollectionRemove::sort($collection, 'name', 'asc');



print_r($sortedCollection);



참고


CollectionRemove::sort 메서드는 컬렉션 내의 요소를 정렬하는 데 사용할 수 있습니다. 이 메서드는 오름차순 또는 내림차순으로 정렬할 수 있습니다. 컬렉션 내의 요소를 정렬하는 데 사용할 수 있는 다양한 옵션을 제공합니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 650 페이지

검색

게시물 검색