1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Laravel】CollectionのsortByとsortByDescメソッド

Posted at

はじめに

今回もLaravelのCollectionのメソッドについてまとめたいと思います。

sortByとsortByDescメソッドでキーを指定して並べ替える

・sortByメソッドで昇順に並び替える

$collection = collect([
    ['id' => 1, 'name' => '山田', 'age' => 18],
    ['id' => 2, 'name' => '佐藤', 'age' => 38],
    ['id' => 3, 'name' => '小林', 'age' => 25],
]);

$sorted = $collection->sortBy('age');

print_r($sorted->toArray());

実行結果は下記になります。

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => 山田
            [age] => 18
        )

    [2] => Array
        (
            [id] => 3
            [name] => 小林
            [age] => 25
        )

    [1] => Array
        (
            [id] => 2
            [name] => 佐藤
            [age] => 38
        )

)

・sortByDescメソッドで降順に並び替える
(sortByの逆の順番になります。)

$collection = collect([
    ['id' => 1, 'name' => '山田', 'age' => 18],
    ['id' => 2, 'name' => '佐藤', 'age' => 38],
    ['id' => 3, 'name' => '小林', 'age' => 25],
]);

$sorted = $collection->sortByDesc('age');

print_r($sorted->toArray());

実行結果は下記になります。

Array
(
    [1] => Array
        (
            [id] => 2
            [name] => 佐藤
            [age] => 38
        )

    [2] => Array
        (
            [id] => 3
            [name] => 小林
            [age] => 25
        )

    [0] => Array
        (
            [id] => 1
            [name] => 山田
            [age] => 18
        )
)

おわりに

いかがでしたでしょうか。
様々な条件で並び替えをして試してみてください。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?