好的,所以我有一个具有这种结构的数组。
[0] => stdClass Object
(
[questionID] => 588
[count] => 2
[answer] => extremely-likely
)
[1] => stdClass Object
(
[questionID] => 588
[count] => 2
[answer] => extremely-unlikely
)
[2] => stdClass Object
(
[questionID] => 588
[count] => 1
[answer] => likely
)
[3] => stdClass Object
(
[questionID] => 588
[count] => 1
[answer] => neither
)
[4] => stdClass Object
(
[questionID] => 588
[count] => 1
[answer] => unsure
)
好的,基本上我首先要从这个数组中找到最高数量(数量)。
所以在上面的例子中它将是2。
现在保存了最高的数字,我想计算出其余数字中2的百分比(最高数字)。
所以从上面的数组中,[2]将是最高数字的50%。
现在我的努力到目前为止如下所示:
private function getFFT($region){
$fft = Question::getFFTCount($this->hw->id);
$numbers = [];
foreach($fft as $answer){
$numbers[] = $answer->count;
}
$findHighest = array_keys($numbers,max($numbers));
return $findHighest;
}
现在,当我print_r($ findHighest)时,我得到以下内容。
Array
(
[0] => 0
[1] => 1
)
有谁知道我怎么能做到这一点?
答案 0 :(得分:1)
如果您只是跟踪最高值,您可以节省在$ numbers数组中存储值的成本/内存。
private function getFFT(){
$fft = Question::getFFTCount($this->hw->id);
foreach($fft as $answer){
if (empty($findHighest) || $answer->count > $highest) {
$highest = $answer->count;
}
}
return $highest;
}
然后,一旦获得了最高价值,只需将计数除以$。如果您需要此方法返回每个方法的百分比数组而不是最高值,则可以执行以下操作:
private function getFFT(){
$fft = Question::getFFTCount($this->hw->id);
foreach($fft as $answer) {
if (empty($findHighest) || $answer->count > $highest) {
$highest = $answer->count;
}
}
$numnbers = [];
foreach($fft as $answer) {
$numbers[] = $answer->count / $highest;
}
return $numbers;
}
此外,您可能不需要传入$ region,因为您没有在函数中的任何位置使用它。
答案 1 :(得分:0)
private function getFFT($region){
$fft = Question::getFFTCount($this->hw->id);
$max=0;
$count=0;
foreach($fft as $answer){
if($answer->count> $max)
{
$max=$answer->count;
$count=1;
}
else if($answer->count== $max)
$count++;
}
$ans = $count/count($fft);
$ans=$ans*100;
return $ans;
}
答案 2 :(得分:0)
我不知道我是否理解你的问题,但这就是我提出的问题:
$numbers = [2, 2, 1, 1, 1];
$countValues = array_count_values($numbers);
$highestNumber = max($numbers);
$frequencyOfHighestNumber = $countValues[$highestNumber];
$percentage = 1 / $frequencyOfHighestNumber;
print $percentage;