I need to calculate the frequency of all values in the array $inputArr
in order to build frequency histogram.
我需要计算数组$ inputArr中所有值的频率,以便构建频率直方图。
$query="SELECT delay FROM TestDB;";
$result=DatabaseConnector::ExecuteQueryArray($query);
$inputArr = array();
foreach ($result as $row) {
$inputArr[] = array($row['delay']);
}
$freq = array_count_values ($inputArr);
But var_dump($freq)
returns array(0). It's strange, because var_dump($inputArr)
returns the following result (just a sample):
但是var_dump($ freq)返回数组(0)。这很奇怪,因为var_dump($ inputArr)返回以下结果(只是一个示例):
array(429) {
[0]=> array(1) { [0]=> string(1) "0" }
[1]=> array(1) { [0]=> string(1) "0" }
[2]=> array(1) { [0]=> string(1) "0" }
[3]=> array(1) { [0]=> string(1) "9" }
[4]=> array(1) { [0]=> string(2) "12" }
[5]=> array(1) { [0]=> string(1) "7" }
[6]=> array(1) { [0]=> string(2) "15" }
[7]=> array(1) { [0]=> string(1) "3" }
[8]=> array(1) { [0]=> string(2) "13" }
[9]=> array(1) { [0]=> string(1) "0" }
[10]=> array(1) { [0]=> string(1) "1" }
[11]=> array(1) { [0]=> string(2) "35" }
[12]=> array(1) { [0]=> string(2) "24" }
[13]=> array(1) { [0]=> string(2) "14" }
[14]=> array(1) { [0]=> string(1) "4" }
[15]=> array(1) { [0]=> string(1) "0" }
[16]=> array(1) { [0]=> string(2) "26" }
[17]=> array(1) { [0]=> string(1) "0" }
As it can be seen from this output, inputArr
has repeating values, e.g. 0. So, why $freq = array(0)
?
从该输出可以看出,inputArr具有重复值,例如,那么,为什么$ freq = array(0)?
2 个解决方案
#1
4
$inputArr[] = array($row['delay']);
You are making each element in $inputArr
an array. You don't need a 2d array here, just do:
您正在使$ inputArr中的每个元素成为一个数组。你这里不需要二维数组,只需:
$inputArr[] = $row['delay'];
#2
5
I would consider skipping the PHP part and changing your SQL statement to do all the work for you:
我会考虑跳过PHP部分并更改您的SQL语句来为您完成所有工作:
SELECT delay, count(*) AS freq FROM TestDB GROUP BY delay;
SELECT delay,count(*)AS freq FROM TestDB GROUP BY delay;
#1
4
$inputArr[] = array($row['delay']);
You are making each element in $inputArr
an array. You don't need a 2d array here, just do:
您正在使$ inputArr中的每个元素成为一个数组。你这里不需要二维数组,只需:
$inputArr[] = $row['delay'];
#2
5
I would consider skipping the PHP part and changing your SQL statement to do all the work for you:
我会考虑跳过PHP部分并更改您的SQL语句来为您完成所有工作:
SELECT delay, count(*) AS freq FROM TestDB GROUP BY delay;
SELECT delay,count(*)AS freq FROM TestDB GROUP BY delay;