2017-03-08 77 views
1

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

回答

0

当你d($items);map()它指的是你原来的数组。如果你在map()里面输入var_dump($item),你会发现它只输出独角兽

$items = [ "dog", "cat", "unicorn" ]; 
$newItems = collect($items) 
    ->reject(function($item) { 
     // Reject cats, because they are most likely evil 
     return $item == 'cat'; 
    })->map(function($item) use ($items) { 
     var_dump($item);//TODO 
    }); 

var_dump($newItems);//TODO 
+0

我也许不清楚 - 我会更新这个问题。我期待在每次迭代中访问*整个*,并可能减少收集 – Chris

0

您可以通过运行诸如$this->all()之类的东西来访问集合的当前状态。

$items = collect(["dog", "cat", "unicorn"]) 
    ->reject(function($item) { 
     return $item == 'cat'; 
    }) 
    ->map(function($item) { 
     dd($item); // current item (dog/unicorn); 
     dd($this->all()); // all items in the collection (dog and unicorn); 
    }); 
+0

你是否愿意? '$ this'指的是当前的对象/实例(是的,可以访问'items'),​​但是$ items仍然是原始的未修改版本。无论如何,这就是我的理解 – Chris

+0

是的,我相信。由于Laravel集合是不可变的,因此'$ this'是指一个集合(在本例中)不包含'cat',因为它在上面的操作中被拒绝。 '$ items'变量指向一个集合,它是集合管道中所有操作的结果。 –

+0

我很欣赏这个答案,但'$ this'指的是当前的上下文 - 例如:https://gist.github.com/cjke/fa0e152b5d57da41e74e5027446984d4'$ this'将引用'RouteServiceProvider' – Chris

相关问题