我正在尝试使用 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/