计算php数组中的平均百分比差异


Calculate average percentage difference in a php array

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 3
    [6] => 1
)

我想知道如何计算数组中当前值和下一个值之间的平均百分比差。如果下一个值较大,则执行如下。(即键[0]-[1]1/2 * 100 = 50)。如果它是一个较小的值,它将执行如下。(即键[4]-[5]= 3/5 * 100 = -60)。

下面将表示我打算用这些百分比计算做什么。

1/2 * 100

2/3 * 100

3/4 * 100

4/5 * 100

3/5 * 100(负)

1/3 * 100(负)


Total/count

这将遍历列表,然后从计数中计算平均值。我已经研究过拆分数组,但不知道还能怎么做。

$count = count($num); 
foreach ($num as $value) {
    array_chunk($num, 1);
    if($value<$value){
    $total1 = $total1 + ($value/$value)*100;
    }
    if($value>$value){
    $total2 = $total2 + ($value/$value)*100;
    }
}
$average = (($total1-$total2)/$count);
print($average);

我明白上面的代码是不正确的,但我希望它揭示了我在哪里得到这个。

您不希望使用foreach,因为您将始终需要两个数组元素。注意,这个代码片段不能保护您不受0值的影响。这些将使您的脚本失败。

$num   = array(1, 2, 3, 4, 5, 3, 1); 
$total = 0;
// The number of percent changes is one less than
// the size of your array.
$count = count($num) - 1;
// Array indexes start at 0
for ($i = 0; $i < $count; $i++) {
    // The current number is $num[$i], and the
    // next is $num[$i + 1]; knowing that it's
    // pretty easy to compare them.
    if ($num[$i] < $num[$i + 1]) {
        $total += (100 * $num[$i] / $num[$i + 1]);
    }   
    else {
        $total += (-100 * $num[$i + 1] / $num[$i]);
    };  
};
echo ($total / $count);