create_function()参数中的未定义变量?

时间:2017-06-02 08:43:13

标签: php

我正在尝试使用create_function来查找特定数组中某个值出现的次数。

    while (!empty($rollcounts)){
        // Take the first element of $rollcounts

        $freq = count(array_filter($rollcounts,create_function("$a","return $a == $rollcounts[0]")));// Count how many times the first element of $rollcounts occurs in the list.

        $freqs[$rollcounts[0]] = $freq; // Add the count to the $frequencies list with associated number of rolls

        for($i=0;$i<count($rollcounts);$i++){ // Remove all the instances of that element in $rollcounts

            if(rollcounts[$i] == $rollcounts[0]){
                unset($rollcounts[$i]);
            }

        }

    } // redo until $rollcounts is empty

我收到“通知”消息抱怨$a中的create_function()。我很惊讶,因为我认为$a只是一个参数。我的php版本不支持create_function()吗? phpversion()返回5.6.30并且我正在使用XAMPP。错误消息:

Notice: Undefined variable: a in /Applications/XAMPP/xamppfiles/htdocs/learningphp/myfirstfile.php on line 34

2 个答案:

答案 0 :(得分:2)

所以,如果我正确地阅读你的问题,我想你想计算数组中每个元素的出现次数?如果是这样,请使用array_count_values,例如[1, 1, 2, 2, 3] - &gt; [1 => 2, 2 => 2, 3 => 1]

$freqs = array_count_values($rollcounts);

这样你可以跳过你的while循环。

答案 1 :(得分:1)

你应该使用像...这样的东西。

$freq = count(array_filter($rollcounts,function($a) {return $a == $rollcounts[0];}));

阅读http://php.net/manual/en/functions.anonymous.php,了解更多关于它们的内容。