我有一个这样的数组:
$array = array(10,25,47,14,45,58,25,29,15,36,45,15,25,27,34);
有没有办法用键输出10个范围的新数组,告诉我使用哪个和频率值?
$result = array(
[x0] => frequency // number of values <= x0
[x1] => frequency // number of values > x0 and <=1
etc..., [x2], ...., [x7], x[8]
[x9] => frequency // number of values >= x9
)
答案 0 :(得分:1)
您可以使用array_count_values()
来计算值
$array = array(10,25,47,14,45,58,25,29,15,36,45,15,25,27,34);
$vals = array_count_values($array);
echo "<pre>"; print_r($vals);
这会给你
Array
(
[10] => 1
[25] => 3
[47] => 1
[14] => 1
[45] => 2
[58] => 1
[29] => 1
[15] => 2
[36] => 1
[27] => 1
[34] => 1
)
答案 1 :(得分:1)
将其用于10个相等的段
$array = array(10,25,47,14,45,58,25,29,15,36,45,15,25,27,34);
$step = (max($array) - min($array)) / 10;
$result = [];
for ($i = min($array); $i < max($array) - $step; $i += $step) {
$res = array_filter($array, function($v) use ($i, $step) {
return ($i <= $v) && $v < $i +$step;
});
$result[$i . '-' . ($i + $step)] = $res;
}
返回:
"10 - 14.8" => 2
"14.8 - 19.6" => 2
"19.6 - 24.4" => 0
"24.4 - 29.2" => 5
"29.2 - 34" => 0
"34 - 38.8" => 2
"38.8 - 43.6" => 0
"43.6 - 48.4" => 3
"48.4 - 53.2" => 0
"53.2 - 58" => 0
答案 2 :(得分:0)
我已经使用数组作为范围边界。这里有4个不规则范围的例子。然后转储已排序的数组,以便更容易查看结果是否符合您的期望。
<?php
$array = array(10,25,47,14,45,58,25,29,15,36,45,15,25,27,34);
$bounds = array(0,10,25,50,100);
$lower = array_shift($bounds);
$range_frequencies = array();
sort($array);
var_dump($array);
foreach($bounds as $upper) {
$range_frequencies[$lower . '-' . $upper] = 0;
foreach($array as $k => $v) {
if($v > $lower && $v <= $upper) {
$range_frequencies[$lower . '-' . $upper]++;
unset($array[$k]);
}
}
$lower = $upper;
}
var_dump($range_frequencies);
输出:
array (size=15)
0 => int 10
1 => int 14
2 => int 15
3 => int 15
4 => int 25
5 => int 25
6 => int 25
7 => int 27
8 => int 29
9 => int 34
10 => int 36
11 => int 45
12 => int 45
13 => int 47
14 => int 58
array (size=4)
'0-10' => int 1
'10-25' => int 6
'25-50' => int 7
'50-100' => int 1
答案 3 :(得分:-1)
根据Manjeet Barnala的回答:
$array = array(10,25,47,14,45,58,25,29,15,36,45,15,25,27,34);
$vals = array_count_values($array);
arsort($vals);
$vals = array_slice($vals,0,10,true);
var_dump($vals);