我有以下数组。在这里,我想计算具有值1的变量fraction
。基于no.of.cucurances,我想做一些操作。我知道的一种方法是,使用foreach
循环数组并使用递增器来识别有多少fraction
具有值1.但我想知道有没有比上面更简单的方法?
有人可以建议我吗?
Array
(
[0] => Array
(
[answer] => <p>
Quiz Test Interoperability</p>
[feedback] =>
[fraction] => 0
)
[1] => Array
(
[answer] => <p>
Quiz Test Interrelationship</p>
[feedback] => <br />
[fraction] => 0
)
[2] => Array
(
[answer] => <p>
Quiz Team Interoperability</p>
[feedback] => <br />
[fraction] => 0
)
[3] => Array
(
[answer] => <p>
Queation Test Interoperability</p>
[feedback] => <br />
[fraction] => 1
)
)
答案 0 :(得分:4)
您可以使用array_reduce()
:
<?php
function countFractionIs1 ($element) {
return ($element['fraction'] == 1) ? 1 : 0;
}
$count = array_reduce($yourarray, "countFractionIs1", 0);