如果你有一個簡單map
使用Laravel集合,你可以很容易地做訪問基集合以下幾點:如何在不破壞流暢鏈的情況下訪問集合映射中的項目?
$items = [ "dog", "cat", "unicorn" ];
collect($items)->map(function($item) use ($items) {
d($items); // Correctly outputs $items array
});
如果使用帶有過濾器/拒絕流暢鏈,$項目不再代表組項目:
$items = [ "dog", "cat", "unicorn" ];
collect($items)
->reject(function($item) {
// Reject cats, because they are most likely evil
return $item == 'cat';
})->map(function($item) use ($items) {
// Incorrectly (and obviously) outputs $items array (including "cat");
// Would like to see the $items (['dog', 'unicorn']) here
d($items);
// Will correctly dump 'dog' on iteration 0, and
// will correctly dump 'unicorn' on iteration 1
d($item);
});
問題
是否有可能訪問或者修改的項目陣列,或alternativel y,以當前狀態訪問收藏集。
Javascript中的類似庫,如lodash,作爲第三個參數傳入集合 - Laravel集合沒有。
更新/編輯
要清楚,我可以這樣做(但它打破了鏈)。我想要做以下事情,但沒有收集的中間存儲。
$items = [ "dog", "cat", "unicorn" ];
$items = collect($items)
->reject(function($item) {
// Reject cats, because they are most likely evil
return $item == 'cat';
});
$items->map(function($item) use ($items) {
// This will work (because I have reassigned
// the rejected sub collection to $items above)
d($items);
// Will correctly dump 'dog' on iteration 0, and
// will correctly dump 'unicorn' on iteration 1
d($item);
});
我也許不清楚 - 我會更新這個問題。我期待在每次迭代中訪問*整個*,並可能減少收集 – Chris