打印出前臂环中有多少雄性和雌性


Print out how much males and female there are in foreach loop

我需要打印出有多少雄性(m)和有多少雌性(v)。我是PHP的新手,很抱歉我不理解这些简单的东西,但我真的在网上找不到。

这是阵列

$aGente = array('jan'=> 'm', 'alice'=> 'v', 'veronica'=> 'v', 'herman'=> 'm','maria'=> 'v', 'angelica' => 'v' , 'nancy' => 'v', 'pieter' => 'm');

这就是我目前所拥有的:

foreach($aGente as $k => $v){
    if($k => $v){
        echo $v;
    }
}

您想要做的是实际计数并将计数保存在变量中,然后返回总数。

$numMales = 0;
$numFemales = 0;
foreach($aGente as $k => $v){
    if($v == "m"){
        $numMales++;
    } else if($v == "v") {
        $numFemales++;
    }
}
echo "You have " . $numMales . " males and " . $numFemales . " females."

您可以使用array_keys php函数:http://php.net/manual/en/function.array-keys.php

使用第二个参数,可以精确计算搜索值。

示例:

$aGente = array('jan'=> 'm', 'alice'=> 'v', 'veronica'=> 'v', 'herman'=> 'm','maria'=> 'v', 'angelica' => 'v' , 'nancy' => 'v', 'pieter' => 'm');
$all_v = array_keys($aGente, 'v');
$all_m = array_keys($aGente, 'm');
echo count($all_v); // gives the number of v
echo count($all_m); // gives the number of m

您可以使用array_count_values函数。

$aGente = array('jan'=> 'm', 'alice'=> 'v', 'veronica'=> 'v', 'herman'=> 'm','maria'=> 'v', 'angelica' => 'v' , 'nancy' => 'v', 'pieter' => 'm');
$count =array_count_values($aGente);
echo "Male Count =>".$count['m'];
echo "<br>";
echo "Female Count =>".$count['v'];

在这种情况下,使用array_count_values函数可能是最简单的方法:

$genders = array_count_values($aGente);
echo "Males: ". $genders['m']. PHP_EOL . "Females: ". $genders['v'];

输出:

Males: 3
Females: 5

http://php.net/manual/en/function.array-count-values.php