【问题标题】:PHP/Laravel check if given 2 values are in collectionPHP/Laravel 检查给定的 2 个值是否在集合中
【发布时间】:2021-01-21 19:28:28
【问题描述】:

我使用的数据库:Mysql

我想遍历一个表的行并检查该行中的两个值是否在集合中(laravel)。

我的设置是:

我有一个看起来像这样的数组

[
 ['foo_id' => 1, 'bar_id' => 31],
 ['foo_id' => 1, 'bar_id' => 55],
 ['foo_id' => 2, 'bar_id' => 32],
]

还有一个像这样的数据库表。

table
+----+-----+-------+
| id | foo|   bar  |
+----+-----+-------+
| 1  |  1  |   31  |
+----+-----+-------+
| 2  |  1  |   55  |
+----+-----+-------+
| 3  |  2  |   32  |
+----+-----+-------+
| 4  |  3  |   87  |
+----+-----+-------+
| .  |  .  |   .   |
+----+-----+-------+

所以在这个例子中,第 1,2 和 3 行匹配我的收藏,但第 4 行不匹配。

我的预期输出应该是,当我遍历表中的所有行时,它将在前 3 行返回 yes,然后在第 4 行返回 false。

提前谢谢你。

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: php mysql laravel collections


【解决方案1】:

你必须在 Collection 上使用过滤器

$return = $collection->filter(function($item) use ($array) {
    foreach ($array as $entry) {
        if ($entry['foo_id'] === $item->foo && $entry['bar_id'] === $item->bar) {
            return true;
        }
    }
);

【讨论】:

    猜你喜欢
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 2023-02-09
    相关资源
    最近更新 更多