我有一个数组,我希望获得所有不同的值。
我的代码很好,直到有一点......
$array_for_19_2=[
["A 1","A 1","A 1","A 2","A 3","A 2","A 1","A 3","A 2","A 1","A 3","A 3","A 2","A 1","A 2"],
["A a","A a","A c","A a","A c","A c","A c","A a","A a","A c","A c","A a","A a","A a","A c"],
["A X","A Y","A Z","A Z","A Z","A Y","A X","A X","A X","A X","A Z","A Z","A X","A Z","A Y"],
["1 a","1 b","1 a","1 a","1 b","1 c","1 b","1 c","1 b","1 a","1 a","1 c","1 b","1 a","1 a"],
["2 a","2 a","2 a","2 a","2 a","2 a","2 a","2 b","2 b","2 a","2 a","2 b","2 a","2 b","2 b"],
["3 b","3 c","3 b","3 c","3 a","3 b","3 c","3 b","3 b","3 b","3 c","3 c","3 a","3 c","3 b"],
["a X","a X","a Z","a Y","a Z","a X","a Y","a Z","a Z","a Z","a X","a X","a Y","a Y","a Z"],
["b Z","b Z","b X","b Z","b Z","b Z","b Z","b X","b Y","b Y","b X","b X","b Y","b Y","b Z"],
["c Y","c Y","c Y","c Y","c Z","c Z","c X","c X","c Z","c Y","c Y","c X","c Z","c Y","c X"],
["1 Z","1 Z","1 X","1 Y","1 X","1 Z","1 X","1 Y","1 Y","1 Z","1 X","1 Z","1 Y","1 Y","1 Y"],
["2 X","2 X","2 Y","2 Z","2 Y","2 X","2 X","2 Z","2 Y","2 Y","2 Y","2 X","2 Y","2 X","2 X"],
["3 X","3 X","3 Y","3 X","3 Y","3 Y","3 Y","3 X","3 Z","3 X","3 X","3 Y","3 Y","3 X","3 Y"]];
foreach (array_count_values($array[$i]) as $key => $value) {
if(strrpos($key, "A")===0 && is_numeric(substr($key,2)))
{$keycount1++;}
else if(strrpos($key, "A")===0 && !is_numeric(substr($key,2))){
array_push($lettersarray, substr($key, 2));
}
$probabilty=round(($value/count($array[$i])),2);
echo "$key - <strong>$value</strong> <br/>Probability: $probabilty<br/>";
$names=str_replace(' ', '', $key);
$newarray[$key]=$probabilty;
}
它适用于所有阵列,除了启动&#34; A X&#34;。我得到的结果如下:
A 1 - 6
Probability: 0.4
A 2 - 5
Probability: 0.33
A 3 - 4
Probability: 0.27
A a - 8
Probability: 0.53
A c - 7
Probability: 0.47
**A X - 5
Probability: 0.33
A Y - 3
Probability: 0.2
A Z - 5
Probability: 0.33
A Z - 1
Probability: 0.07
A X - 1
Probability: 0.07**
1 a - 7
Probability: 0.47
1 b - 5
Probability: 0.33
1 c - 3
Probability: 0.2
2 a - 10
Probability: 0.67
2 b - 5
Probability: 0.33
3 b - 7
Probability: 0.47
3 c - 6
Probability: 0.4
3 a - 2
Probability: 0.13
a X - 5
Probability: 0.33
a Z - 6
Probability: 0.4
a Y - 4
Probability: 0.27
b Z - 7
Probability: 0.47
b X - 4
Probability: 0.27
b Y - 4
Probability: 0.27
c Y - 7
Probability: 0.47
c Z - 4
Probability: 0.27
c X - 4
Probability: 0.27
1 Z - 5
Probability: 0.33
1 X - 4
Probability: 0.27
1 Y - 6
Probability: 0.4
2 X - 7
Probability: 0.47
2 Y - 6
Probability: 0.4
2 Z - 2
Probability: 0.13
3 X - 7
Probability: 0.47
3 Y - 7
Probability: 0.47
3 Z - 1
Probability: 0.07
为什么我两次获得相同的值?
答案 0 :(得分:0)
这将返回所有值的计数。
$res = array_icount_values ($array);
echo '<pre>';print_r($res);
function array_icount_values($arr, $lower = true) {
$arr2 = array();
if (!is_array($arr['0'])) {
$arr = array($arr);
}
foreach ($arr as $k => $v) {
foreach ($v as $v2) {
if ($lower == true) {
$v2 = strtoupper($v2);
}
if (!isset($arr2[$v2])) {
$arr2[$v2] = 1;
} else {
$arr2[$v2]++;
}
}
}
return $arr2;
}