循环遍历 Laravel 集合以检查相同的值

问题描述

我将感谢您对解决此问题的任何帮助。我正在从事 Laravel 项目。我有一个这样的收藏; $products = Product::all(); 集合中的每个产品都有一个名为 status 的列,该列设置为 0、1 或 2。现在我想遍历我的集合,如果所有产品状态值都返回 0,我想在前端,否则显示其他内容。我已经尝试过了,但无法达到我想要的效果

   $status = 0;
   foreach($products as $product){
      if($product->status == 0{
          $status = 0;
          return "exhausted";
      }
      return "not exhausted";
    }

解决方法

您可以使用Collection::every()

if ($products->every(fn($product) => $product->status === 0)) {
    return "exhausted";
}
return "not exhausted";
,

那怎么办,如果只有当所有状态都为 0 时:

   $status = "exhausted";
   foreach($products as $product){
      if($product->status != 0){
         $status = "not exhausted";
         break;
      }
   }
   return $status;
,

可以使用 Eloquent 获取一个 Collection,然后使用 Collection 的 count 方法。示例:

$products = Product::all();
$count = $products->whereStatus(0)->get()->count();
return $count == 0 ? "Exhausted": "WhatEverYouwant";

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...