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"
]
}
]
}
無事インデックスが振り直されました
他の言語触ってるとこういうこと忘れてしまいがちなので気を付けたいですね