如果你有一个简单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