【发布时间】:2017-08-24 07:00:53
【问题描述】:
我不明白,我有一些物品。 在这种情况下,该集合在索引 1 处仅包含一项,因为它是从更大的集合中过滤出来的。 关键是如何获得我需要的唯一数据,而不必重置索引的值然后在索引 0 处访问? 在这种情况下,我将始终在集合中只有一个项目,但索引可能不同,因此默认情况下我不能使用 [0] 索引。
//returns all items with 'item_color_id" = 1
$item = Item::where(//some constraints);
$filtered = $item->filter(function ($i) {
return $i->item_color_id == 1;
});
if (count($filtered)) {
//need to access a single data inside the collection
// like for example 'item_brand_id'
//I can do it like this:
$filtered = $filtered->values();
$item_brand_id = $filtered[0]['item_brand_id'];
//but what sense does it have?? how can we access 'item_brand_id'
//from $filtered without resetting the indexes?
}
我们没有直接访问数据的方法对我来说没有任何意义,或者如果我们有它我错过了它。 例如,我可以像这样在 $filtered 上使用 max() 或 min():
$max_brand_id = $filtered->max('item_brand_id');
我知道在这种情况下找到最大id没有任何意义,但它表明我们可以在一个段落中找到数据。
我试过only('item_brand_id);,但是当数据在那里时返回空。
【问题讨论】:
-
那么集合
$item的一件物品来自哪里? -
那是另一个集合,为了访问过滤后的数据有什么区别?
标签: php laravel collections