php - create_function() 参数中 undefined variable ?

标签 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

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

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

最佳答案

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

$freqs = array_count_values($rollcounts);

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

关于php - create_function() 参数中 undefined variable ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44324513/

相关文章:

php - 达到最大 APache 连接数 - 我被黑了吗?

PHP 嵌入图像未在 Web 浏览器上显示

php - 使用循环为 WHERE 子句创建查询

php - 重定向后重新填写表格

php_zip 在 php 5.3.5 中不存在

php - JSON复杂格式

javascript - 从函数返回两个变量

PHP 错误跟踪器 : storing attached files

php - 更改文件(图像)输入ajax无法发布文件

php - 将来自 2 个 php 文件的 2 个查询加在一起