1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

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

はじめに

今回も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
        )
)

おわりに

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?