如何验证项目是否存在于包含对象的数组中


How to verify an item exists in an array with objects?

>我有一个名为items的对象数组:

Array 
( 
    [0] => stdClass Object 
        (   
            [id] => 1 
            [libelle_fr] => service un 
            [libelle_en] => service one 
            [prix] => 1111.222 
        ) 
    [1] => stdClass Object 
        ( 
            [id] => 2 
            libelle_fr] => serivce deux 
            [libelle_en] => service tow 
            [prix] => 2222.222
        )
    [2] => stdClass Object 
        ( 
            [id] => 3 
            [libelle_fr] => service trois 
            [libelle_en] => service three 
            [prix] => 333.33 
        )  
) 

我想看看 items 数组中是否存在 id 号 5,或者类的任何其他成员。

您还可以使用茴香酒中的FluentFunctions

 $result = Arrays::any($array, FluentFunctions::extractField('id')->equals(5));

使用来自茴香酒的数组:

$result = Arrays::any($array, function($element) {
    return $element->id == 5;
});

只需循环数组:

$input  = array(); // your input data
$exists = false;
foreach ($input as $item) {
  if ($item->id == 5) {
    $exists = true;
   break;
  }
}

您还可以使用array_reduce

$exists = array_reduce($input, function($result, $item){
  return $result || $item->id == 5;
}, false);