如何检查或声明数组的数组值,例如类/实体的实例


how to check or declare array values of an array like an instanceof a Class/Entity

在我的symfony项目中,我有一个数组$productContainer,其中包含一些值,例如(php dump):

array:2 [▼
  0 => "value1"
  1 => "value2"
]

我通过控制器中的findBy方法在Product实体中传递此数组,如下所示:

$products = $this->getDoctrine()->getRepository('MyBundle:Product')
                                ->findByValue($productContainer);

findBy 方法和数组值之间的结果非常匹配。

但是当我检查数组是否是我的实例Product如下所示:

dump($products instanceof Product);
die;

它重新调整我:

我知道$products是一个数组而不是一个对象,但是如何将我的数组$products声明为instanceof Product实体?

编辑

为了更精确,我需要声明或检查我的数组$products值是否instanceof Product,因为在同一控制器中,我必须在 queryBuilder 中为另一个实体传递数组$products,如下所示:

$entity = $this->getDoctrine()->getRepository('MyBundle:Entity')
                              ->getEntityWithProducts($slug, $products);

我用$_POST方法恢复数组$productsRequest $request)这是一个我重新调整到 JsonResponse 中的控制器方法,这就是我以这种方式进行的原因。

如果您只需要一种产品,请尝试findOneByValue而不是findByValue
或从收到的数组中提取某个元素,因为您在调用 findByValue 后会收到实体数组。
或遍历接收数组中的所有元素以检查它们。
或也许在您的产品存储库中,存在为您做一些员工的方法findByValue

但无论如何,在学说之后检查它为你返回适当的类实例听起来很奇怪......
如果使用类似 getArrayResult 的内容,您将收到数组,否则您将收到相应实体的实例。

数组不能

是某个对象类,但如果我了解你想做什么,也许你可以尝试使用数组函数。

试试这个

$test = array_reduce(
          $products, 
          function ($condition, $item) {
            return $condition && $item instanceof Product;
          }, 
          true
        );
// $test will be true if all elements of $products are instances 
// of 'Product', false otherwise