PHP - 计算特定的数组值,多个值

时间:2014-07-09 08:47:08

标签: php arrays count

如何计算数组中多个值的出现次数?

我在stackoverflow上找到了,

$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];

我已经使用过这个,但是我无法让它工作,必须有一个更优雅的方式,

$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Mary","Ben");
$counts = array_count_values($array);
$1 = $counts['Ben'];
$2 = $counts['Phil'];
$3 = $counts['Mary'];
echo $1+$2+$3;

2 个答案:

答案 0 :(得分:2)

// change your code to this
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Mary","Ben");
$counts = array_count_values($array);
$one = $counts['Ben']; // 3
$two = $counts['Phil']; // 1
$three = $counts['Mary']; // 2
echo $one + $two + $three; // 6

// because of this :)
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var";      // outputs "Bob, Joe"
$4site = 'not yet';     // invalid; starts with a number <-- your case
$_4site = 'not yet';    // valid; starts with an underscore
$täyte = 'mansikka';    // valid; 'ä' is (Extended) ASCII 228.
$bar = &$foo;           // This is a valid assignment.
$bar = &(24 * 7);       // Invalid; references an unnamed expression.

更多关于PHP variables

答案 1 :(得分:0)

如果你想在不使用array_count_values()函数的情况下计算,则使用此代码

    $array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");

$len = sizeof($array);

$i = 0;
$occurance = 0;

while( $i < $len )

{

    if($array[$i] == 'Ben')
    {
        $occurance++;
    }

    $i++;
}

echo 'number of occurance of Ben ='.$occurance;