簡體   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