我有一个二维数组,如下所示:
$array1 = array
(
array(1, "Harry", "Male", 30),
array(2, "Troy", "Male", 4),
array(3, "Vicky", "Female", 22),
);
我想返回第四个“列”超过固定数目10的次数
例如,我正在追踪以下内容:
MalesUnder10 =
MalesOver10 =
FemalesUnder10 =
MalesOver10 =
谢谢
答案 0 :(得分:3)
您可以使用array_filter
来过滤数组。使用count
对结果进行计数
$array1 = array (
array(1, "Harry", "Male", 30),
array(2, "Troy", "Male", 4),
array(3, "Vicky", "Female", 22),
);
$MalesUnder10 = count(array_filter( $array1, function( $o ){
return $o[2] == "Male" && $o[3] < 10;
}));
$MalesOver10 = count(array_filter( $array1, function( $o ){
return $o[2] == "Male" && $o[3] > 10;
}));
$FemalesUnder10 = count(array_filter( $array1, function( $o ){
return $o[2] == "Female" && $o[3] < 10;
}));
$FemalesOver10 = count(array_filter( $array1, function( $o ){
return $o[2] == "Female" && $o[3] > 10;
}));
这将导致:
$MalesUnder10 = 1
$MalesOver10 = 1
$FemalesUnder10 = 0
$FemalesOver10 = 1
注意:10岁的人并不指望逻辑。您可以通过$o[3] => 10
或$o[3] =< 10
这里是live Demo。多亏尼克
答案 1 :(得分:0)
这可能会帮助您使用简单的计数器和foreach
对这些变量进行计数:
$array1 = array
(
array(1, "Harry", "Male", 30),
array(2, "Troy", "Male", 4),
array(3, "Vicky", "Female", 22),
array(3, "Sharon", "Female", 9),
);
$MalesUnder10 = $MalesOver10 = $FemalesUnder10 = $FemalesOver10 = 0;
foreach ($array1 as $arr) {
switch ($arr[3]) {
case $arr[3] > 10:
if ($arr[2] === "Male") {
$MalesOver10++;
} else {
$FemalesOver10++;
}
break;
default:
if ($arr[2] === "Female") {
$MalesUnder10++;
} else {
$FemalesUnder10++;
}
break;
}
}
var_dump("Number of Males Under 10 is " . $MalesUnder10);
var_dump("Number of Males Over 10 is " . $MalesOver10);
var_dump("Number of Females Under 10 is " . $FemalesUnder10);
var_dump("Number of Females Over 10 is " . $FemalesOver10);
string(29) "Number of Males Under 10 is 1"
string(28) "Number of Males Over 10 is 1"
string(31) "Number of Females Under 10 is 1"
string(30) "Number of Females Over 10 is 1"