检查多维数组中的多个条件

Check multiple conditions in multidimensional array

我想检查数组中的水果名称并检查颜色值是否为1。它显示错误Cannot use object of type stdClass as array

if(checkFruits('apple','red')){
   //ok 
}
function checkFruits($fruit = null, $color = null) {
 $fruits = Array ( [0] => stdClass Object ( [id] => 1 [fruit] => apple [red] => 1 [yellow] => 0 [1] => stdClass Object ( [id] => 2 [fruit] => orange [red] => 0 [yellow] => 1 ) );
 foreach($fruits as $val){
     if($val['fruit'] == $fruit && $val[$color] == 1){
          return true;
     }
  }
 return false;
}

您正在遍历 $fruit 参数,这是一个标量变量而不是 $fruits 数组。

另外你创建数组的代码也行不通我也改了

function checkFruits($fruit = null, $color = null) {
    $fruits = (object) [
                    (object) ['id' =>1, 'fruit' => 'apple', 'red' => 1, 'yellow' => 0],
                    (object) ['id' =>1, 'fruit' => 'orange', 'red' => 0, 'yellow' => 1]
        ];

    foreach($fruits as $val){
        if($val->fruit == $fruit && $val->{$color} == 1){
             return true;
        }
     }
    return false;
}

if (checkFruits('apple', 'red')) {ECHO 'YES Apples are red';}

结果

YES Apples are red

可以使用关联数组

  if(checkFruits('apple','red')){
       echo "ok";
    }
    
    function checkFruits($fruit = null, $color = null) {
    
     $fruits = array(
         array("id" => 1,"fruit" => 'apple',"red" => 1,"yellow" => 0),
         array("id" => 2,"fruit" => 'orange',"red" => 0,"yellow" => 1 )
     );
     
     foreach($fruits as $val){
         if($val['fruit'] == $fruit && $val[$color] == 1){
              return true;
         }
      }
      
     return false;
     
    }