使用array_count_values会产生foreach循环

时间:2017-07-13 08:33:50

标签: php

我有array个ID,很多ID都出现多次,而我正在使用array_count_values()来计算每个ID发生的次数。

如果特定ID出现超过3次,我想做点什么,我只是想不出如何将array_count_values()结果变成foreach循环,所以我可以使用它。

任何帮助表示赞赏!

$array = array("297","297","297","297","188","188"); 

print_r( array_count_values($array) );

// loop room booking data
foreach($array as $key => $val) {

    // if the ID occurs more than 3 times
    if ( $val > '3' ) {
        // do something
    }

}

2 个答案:

答案 0 :(得分:3)

将函数的结果分配给变量,然后遍历该变量。

$frequencies = array_count_values($array);
foreach ($frequencies as $id => $count) {
    if ($count > 3) {
        echo "$id occurs $count times<br>";
    }
}

答案 1 :(得分:1)

array_count_value结果分配给变量并将此值传递给foreach循环,如下所示

    <?php 
    $array = array("297","297","297","297","188","188"); 

    $array1 = array_count_values($array); // assign result to array1 variable

    // loop room booking data
    foreach($array1 as $key => $val) {

        // if the ID occurs more than 10 times
        if ( $val > '3' ) {
            // do something
            echo $key; // return value e.g 297
            echo $value; // return no. of times ID occure e.g. 4

        }

    }
    ?>

running Code