计算键在数组中的对象中具有ans =“ true”的次数

时间:2019-04-03 10:00:32

标签: php arrays multidimensional-array

我有这个数组。

array (size=5)
      0 => 
        object(stdClass)[37]
          public 'options' => string 'test 1' (length=6)
          public 'answer_check' => string 'false' (length=5)
          public 'justify_answer' => string 'test 1' (length=6)
          public 'score' => string '0' (length=1)
          public 'admin_id' => string '3' (length=1)
          public 'approved' => string 'approve' (length=7)
      1 => 
        object(stdClass)[38]
          public 'options' => string 'test 1' (length=6)
          public 'answer_check' => string 'true' (length=4)
          public 'justify_answer' => string 'test 2' (length=6)
          public 'score' => string '0' (length=1)
          public 'admin_id' => string '3' (length=1)
          public 'approved' => string 'approve' (length=7)
      2 => 
        object(stdClass)[39]
          public 'options' => string 'test 3' (length=6)
          public 'answer_check' => string 'true' (length=4)
          public 'justify_answer' => string 'test 3' (length=6)
          public 'score' => string '0' (length=1)
          public 'admin_id' => string '3' (length=1)
          public 'approved' => string 'approve' (length=7)

我想做的是

多少次 answer_check =“ true”

不使用循环。

有什么办法吗?

2 个答案:

答案 0 :(得分:1)

Filter array,然后是其中的count个值:

echo count(array_filter(
    $array, 
    function($v) { return $v->answer_check === 'true'; }
));

答案 1 :(得分:0)

更简洁的代码。结合array_columnarray_count_values

echo array_count_values(array_column($array, "answer_check"))["true"];