PHP数组中子键的平均值


PHP Average of subkeys in an array

Array (
  [JohnDoe] => Array (
  [id] => 23
  [name] => JohnDoe
  [logintimes] => 30
)
 [JaneDoe] => Array (
  [id] => 26
  [name] => JaneDoe
  [logintimes] => 9
)
 [Smith] => Array (
  [id] => 35
  [name] => Smith
  [logintimes] => 9
 )
)

如何将登录时间相加(然后找到它们的平均值)

很容易循环得到

$counter = 0;
$total = 0;
foreach($array as $row) {
    $counter++;
    $total += $row['logintimes'];
}
echo $total / $counter;

您也可以使用array_sumarray_map:

$sum = array_sum(array_map(function($item) { 
    return $item['logintimes']; 
}, $your_array));
echo $sum / count ($your_array);

为完整起见,PHP>= 5.5.0:

$average = array_sum(array_column($array, 'logintimes')) / count($array);

您必须循环遍历数组,并使用子数组引用来累计logintimes值。完成后,只需将logintimes的总数除以数组项的数量。

例子:

<?php
$users = array(
    "JohnDoe" => array(
        "id" => 23,
        "name" => "JohnDoe",
        "logintimes" => 30
    ),
    "JaneDoe" => array(
        "id" => 23,
        "name" => "JaneDoe",
        "logintimes" => 9
    ),
    "Smith" => array(
        "id" => 35,
        "name" => "Smith",
        "logintimes" => 9
    )
);
$count = 0;
$total = 0;
foreach($users as $user => $values) {
    $count++;
    $total += $values['logintimes'];
}
$average = $total / $count;
echo $average;  //Output 16

工作示例:http://codepad.org/uHpJnODv

认为这个解决方案应该更有效(PHP 5.5+):

 <?php
$users = array(
    "JohnDoe" => array(
        "id" => 23,
        "name" => "JohnDoe",
        "logintimes" => 30
    ),
    "JaneDoe" => array(
        "id" => 23,
        "name" => "JaneDoe",
        "logintimes" => 9
    ),
    "Smith" => array(
        "id" => 35,
        "name" => "Smith",
        "logintimes" => 9
    )
);
$count = count($users);
$average = array_column($users , 'logintimes') / $count;
echo $average;  //Output 16