繁体   English   中英

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

[英]PHP - count specific array values, multiple values

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

我在下面的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;
// 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变量的更多信息

如果您想在不使用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM