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
)
)
我如何通过向对方添加登录时间(然后找到它们的平均值?)
答案 0 :(得分:3)
循环并获得
非常简单$counter = 0;
$total = 0;
foreach($array as $row) {
$counter++;
$total += $row['logintimes'];
}
echo $total / $counter;
答案 1 :(得分:2)
您也可以使用array_sum
和array_map
执行此操作:
$sum = array_sum(array_map(function($item) {
return $item['logintimes'];
}, $your_array));
echo $sum / count ($your_array);
答案 2 :(得分:1)
为了完整性,PHP> = 5.5.0:
$average = array_sum(array_column($array, 'logintimes')) / count($array);
答案 3 :(得分:0)
您必须遍历数组,并使用子数组引用来总计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
答案 4 :(得分:0)
认为此解决方案应该更有效(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