【问题标题】:How to search item of collection with key?如何用键搜索收藏项?
【发布时间】:2018-01-20 17:29:30
【问题描述】:

我得到了以下收藏:

$this->items = collect([$productId => [
                    'name' => $product->title,
                    'price' => $product->price,
                    'is_sale' => $product->is_sale,
                    'sale_price' => $product->sale_price,
                    'sale_percent' => $product->sale_percent,
                    'can_use_promocode' => $product->can_use_promocode,
                    'qty' => 1,
                ]);
]);

如何使用键搜索项目?在文档中 (https://laravel.com/docs/5.2/collections) 我没有看到任何方法

UPD:例如,用户将商品添加到购物车 ($this->items)。我想检查购物车中是否存在物品(需要用钥匙来做)。用于 php 函数 array_key_exists 的模拟,但用于集合。

【问题讨论】:

  • 你想在这里搜索什么??
  • @Sohel0415 检查问题,更新:)
  • 你要搜索它,用哪一个键?

标签: php laravel


【解决方案1】:

使用has()

if($this->items->has('key_name_to_check')){
    ///your task if exists
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    $this->items->toArray()[$key]
    

    或者你可以使用first()方法:

    $this->items->first(function($i, $k) use($key) {
        return $key === $k;
    });
    

    更新

    如果您只想知道集合中是否存在具有给定键的项目,可以使用offsetExists() 方法。

    offsetExists() 方法完全类似于 array_key_exists(),因为它所做的只是:

    return array_key_exists($key, $this->items);
    

    【讨论】:

    • 集合不存在类似array_key_exists 的方法? :(
    • @Alexxosipov offsetExists()array_key_exists() 的模拟,但它是用于集合的。
    • 哦,正如@Sohel0415 所说,我可以使用 has() 来实现它:) 但你的想法也很好,如果不存在,我只需要获取 true 或 false :)
    • @Alexxosipov has()offsetExists() 的包装器。 has() 将键转换为数组,然后对其进行迭代并调用offsetExists()。是的,你也可以使用这种方法。
    • 感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 2013-06-02
    相关资源
    最近更新 更多