LoginSignup
1
0

More than 5 years have passed since last update.

Laravelのコレクションをfilterするとインデックスがずれる

Last updated at Posted at 2018-09-04

Laravelのコレクションのfilterはarray_filterを使用しているためインデックスがずれてしまいます

なぜarray_filterでインデックスがずれるかは
PHPの配列array_filter
をご参照ください

簡単なコレクションを作成


$collection = collect([]);
$collection->push(collect(['id' => 1, 'name' => 'A']));
$collection->push(collect(['id' => 2, 'name' => 'B']));
$collection->push(collect(['id' => 3, 'name' => 'C']));

dump($collection);

Illuminate\Support\Collection {#26de15
  #items: array:3 [
    0 => Illuminate\Support\Collection {#2623
      #items: array:2 [
        "id" => 1
        "name" => "A"
      ]
    }
    1 => Illuminate\Support\Collection {#2609
      #items: array:2 [
        "id" => 2
        "name" => "B"
      ]
    }
    2 => Illuminate\Support\Collection {#2616
      #items: array:2 [
        "id" => 3
        "name" => "C"
      ]
    }
  ]
}

これをfilter

$filterd = $collection->filter(function ($v) {
  return $v['id'] > 1
});

dump($filterd);

Illuminate\Support\Collection {#2610
  #items: array:2 [
    1 => Illuminate\Support\Collection {#2609
      #items: array:2 [
        "id" => 2
        "name" => "B"
      ]
    }
    2 => Illuminate\Support\Collection {#2616
      #items: array:2 [
        "id" => 3
        "name" => "C"
      ]
    }
  ]
}

この時点でインデックス0がなくなったことがわかります

解決策

基本的にはarray_filterでずれてるだけなので以下の記事のようにarray_valueを使用します
PHP の array_filter を通すとインデックスに差が生まれる

しかしLaravelのコレクションの場合valuesメソッドとして用意されているのでこちらを使用します。

$filterd = $collection->filter(function ($v) {
  return $v['id'] > 1
})->values();

dump($filterd);

Illuminate\Support\Collection {#2596
  #items: array:2 [
    0 => Illuminate\Support\Collection {#2609
      #items: array:2 [
        "id" => 2
        "name" => "B"
      ]
    }
    1 => Illuminate\Support\Collection {#2616
      #items: array:2 [
        "id" => 3
        "name" => "C"
      ]
    }
  ]
}

無事インデックスが振り直されました

他の言語触ってるとこういうこと忘れてしまいがちなので気を付けたいですね

参考

Laravelでコレクションをfilterするとインデックスが連続でなくなる

1
0
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
0