LoginSignup
2

More than 5 years have passed since last update.

laravelのcollectionをフィルタリングしてkeyを振り直す

Last updated at Posted at 2018-09-13

背景

既知の人も多いでしょうが、
なんか良いやり方がパッと思いつかなかったので備忘録に。

ちなみにlaravel5.5です

何がしたいのか

laravelのcollectionにて
集計したデータをフィルタリングして、
collectionのkeyを順番に振り直したい

フィルタリング

$collection = Collection::make([
   ["id" => "1", "is_use" => true],
   ["id" => "2", "is_use" => true],
   ["id" => "3", "is_use" => false],
   ["id" => "4", "is_use" => true],
]);

例えばこういったコレクションがあるとして、
is_useがtrueのものだけを集計したいとする

$filtered = $collection->filter(
    function ($value) {
        return $value['is_use'];
    }
);

dd(filtered)

こういった感じでフィルタリングしてやると

Collection {
  [
    0 => [
      "id" => "1"
      "is_use" => true
    ]
    1 => [
      "id" => "2"
      "is_use" => true
    ]
    3 => [
      "id" => "4"
      "is_use" => true
    ]
  ]
}

キー「2」が抜け番になっちまった。。。

それだと使いにくいことがある(あった)ので、

$filtered = $collection->filter(
    function ($value) {
        return $value['is_use'];
    }
)->values();

dd($filtered)

valuesをチェーンしてやると

Collection {
  [
    0 => [
      "id" => "1"
      "is_use" => true
    ]
    1 => [
      "id" => "2"
      "is_use" => true
    ]
    2 => [
      "id" => "4"
      "is_use" => true
    ]
  ]
}

って感じで振り直してくれる。

追記

チェーンするvaluesは関数なので「()」をつけねばなりません。
@nunulkさん、ご指摘ありがとうございました。

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
2