使用array_reduce从数组中查找平均数

时间:2017-09-27 13:28:05

标签: php arrays function

我有一个由人名和身高组成的数组。我需要使用函数array_reduce找到平均高度,该函数包含在分配给变量的函数中。下面是我到目前为止编写的代码。一切似乎都在工作,直到我将数组传递给array_reduce函数,然后该函数为NULL。我试着用代码中的注释来解释它。为什么数组突然被删除,我如何将它传递给最内部的函数?

$people = [
  ['name'=> 'John'  , 'height'=> 1.65],
  ['name'=> 'Peter' , 'height'=> 1.85],
  ['name'=> 'Silvia', 'height'=> 1.69],
  ['name'=> 'Martin', 'height'=> 1.82]
];


$filter = function  ($people)
{
    $averageHeight = 0;
    $count = count($people);
    echo $count;
    //if I var_dump($people) - the array $people is FINE.
    return array_reduce(
            $people,
            function ($people) use (&$averageHeight, &$count)
            {
                $averageHeight += $people['height'] / $count;    
                return $averageHeight;
                //var_dump($people); - var people is NULL. Where did it go?
            }
    );
};

print_r($filter($people));

2 个答案:

答案 0 :(得分:1)

这是您使用array_reduce获取平均值的方法:

function array_average($array) {
    $carry = null;
    $count = count($array);
    return array_reduce($array, function ($carried, $value) use ($count) {
         return ($carried===null?0:$carried) + $value/$count;
    },$carry);
}

该函数将累加器和值作为参数,并应返回要传递给下一个元素的值。

您可以将其用作:

 $averageheight = array_average(array_column($people,"height"));

这导致:

  

1.7525

以下是一个例子:

http://sandbox.onlinephpfunctions.com/code/a0bd15fb66061340ceca9e743418575d7990b6c3

如果您需要将整个事情作为可调用者,那么请执行:

function array_average($array) {
    $carry = null;
    $count = count($array);
    return array_reduce($array, function ($carried, $value) use ($count) {
         return ($carried===null?0:$carried) + $value/$count;
    },$carry);
}

$filter = function ($people) {
     return array_average(array_column($people,"height"));
};

 print_r($filter($people));

http://sandbox.onlinephpfunctions.com/code/dd2ec178be3989f8d9dd9d9ef5d270c7d40b8be7

答案 1 :(得分:0)

Use this code, where the total array count we didn't find out inside the sum function so, i will use this into the print_r() function.


<?php

function sum($carry, $p)
{
    $carry += $p['height'];
    return $carry;
}

$people = [
  ['name'=> 'John'  , 'height'=> 1.65],
  ['name'=> 'Peter' , 'height'=> 1.85],
  ['name'=> 'Silvia', 'height'=> 1.69],
  ['name'=> 'Martin', 'height'=> 1.82]
];

$k = 0;
$k = array_reduce($people ,"sum");
print_r($k/count($people));
?>