php 如何对多个平面数组中的数据列求平均值?

z31licg0  于 2023-03-07  发布在  PHP
关注(0)|答案(5)|浏览(138)

假设我有4个数组,每个数组中的值数量相同:

$array1 = array(0, 7, 5, 0);
$array2 = array(2, 6, 10, 0);
$array3 = array(4, 8, 15, 10);
$array4 = array(6, 7, 20, 10);

我想计算所有4个数组的平均值,得到如下结果:

array(3, 7, 12.5, 5);
0s7z1bwu

0s7z1bwu1#

对于更动态的用法,例如6个数组或更多,您可以使用以下代码:

$all_arrays = [
    array(0, 7, 5, 0),
    array(2, 6, 10, 0),
    array(4, 8, 15, 10),
    array(6, 7, 20, 10),
    array(1, 2, 3, 4),
    array(5, 6, 7, 8),
    // more arrays
];

$each_array_count = count($all_arrays[0]); // 4
$all_arrays_count = count($all_arrays); // 6

$output = [];

for ($i = 0; $i < $each_array_count; $i++) {
    for ($j=0; $j < $all_arrays_count; $j++) { 
        $output[$i] += $all_arrays[$j][$i] / $all_arrays_count;        
    }
}

echo "<pre>";
var_dump($output);

输出:(Demo

Warning: Undefined array key 0 in /in/E783F on line 20

Warning: Undefined array key 1 in /in/E783F on line 20

Warning: Undefined array key 2 in /in/E783F on line 20

Warning: Undefined array key 3 in /in/E783F on line 20
<pre>array(4) {
  [0]=>
  float(3)
  [1]=>
  float(6)
  [2]=>
  float(10)
  [3]=>
  float(5.333333333333333)
}
g0czyy6m

g0czyy6m2#

* 全动态功能:*

我承担了构建一个完全动态的函数的任务,在这个函数中,你可以输入任意多的数组,我还添加了一个null检查,如下面的例子所示,以防你需要跳过数组中的值。

功能:

# Function takes in unlimited arrays,
# and returns the average of each index of 
# those arrays as a new array.
function arrayAverage(...$array){

    # Loop through the arrays in the input arguments.
    # For every array, extract all numeric values from each
    # element, and group them by index in a temporary
    # multi-dimensional array. If a value is null, or 
    # cannot be converted into an integer/float, skip it.
    foreach($array as $arr){
        for($i = 0; $i < count($arr); $i++){
            if(!is_null($arr[$i]) && ($arr[$i] == (int)$arr[$i]))
                $temparr[$i][] = (int)$arr[$i];
            elseif(!is_null($arr[$i]) && ($arr[$i] == (float)$arr[$i]))
                $temparr[$i][] = (float)$arr[$i];
        }
    }
        

    # Loop through the multi-dimensional array, and calculate the average
    # of each sub-array. Store each result in a separate array to be 
    # returned after the loop is finished.
    for($j = 0; $j < count($temparr); $j++)
        $averages[] = array_sum($temparr[$j]) / count($temparr[$j]);
    
    # Return aforementioned array containing the averages. 
    return $averages;

}

用法/示例:

# Arrays can have a different amount of key=>value pairs,
# and integer values stored as strings can be parsed,
# as shown in "$array2".
$array1 = array(0, 7, 5, 0);
$array2 = array(2, 6, 10, 0, "100");
$array3 = array(4, 8, 15, 10);
$array4 = array(6, 7, 20, 10);

# Example on how to skip values just in case the need arises
# (So averages won't be affected by having an extra number)
$array5 = array(null, null, null, null, 300);

$averages = arrayAverage($array1, $array2, $array3, $array4, $array5);
print_r($averages);

输出:

Array
(
    [0] => 3
    [1] => 7
    [2] => 12.5
    [3] => 5
    [4] => 200
)

实时沙盒演示:

https://onlinephp.io/c/bb513

xpszyzbs

xpszyzbs3#

这是一个简单的解决方案,但你可以进一步推广它,使其通用,但它现在将工作。它可以相应地更新:
注意:假设数组的计数与您提到的相同

$result = [];
     for ($i = 0; $i < count($array1); $i++) {
         $result [] = ($array1[$i] + $array2[$i] + $array3[$i] + $array4[$i]) / count($array1);
     }
     dd($result);
7xzttuei

7xzttuei4#

另一种方法:

$arrays = [$array1, $array2, $array3, $array4];

$result = [];
for ($i = 0; $i < count($array1); $i++) {
    $result[] = array_sum(array_column($arrays, $i)) / count($arrays);
}

工作example

nxagd54h

nxagd54h5#

对于一个简洁的函数式代码片段,可以使用array_map()来"转置"数据行,这意味着数据列将被传递给自定义函数,然后执行平均值计算。
代码:(Demo

$array1 = [0, 7, 5, 0];
$array2 = [2, 6, 10, 0];
$array3 = [4, 8, 15, 10];
$array4 = [6, 7, 20, 10];

var_export(
    array_map(
        fn() => array_sum(func_get_args()) / func_num_args(),
        $array1,
        $array2,
        $array3,
        $array4
    )
);
// fn(...$col) => array_sum($col) / count($col), would also work

输出:

array (
  0 => 3,
  1 => 7,
  2 => 12.5,
  3 => 5,
)

注意,当数组长度不完全相同时,此技术将用null(计为0)填充列中的间隙:Demo.
如果输入数组是一个多维数组,可以使用spread操作符将其解包为array_map()

var_export(array_map(fn() => array_sum(func_get_args()) / func_num_args(), ...$arrays));

要防止null值扭曲计算,请在计算之前过滤它们:Demo.

var_export(
    array_map(
        fn(...$col) => array_sum($col) / count(array_filter($col, fn($v) => !is_null($v))),
        ...$arrays
    )
);
// or:  fn(...$col) => array_sum($col) / count(array_diff($col, ['']))

相关问题