关于Stack Overflow也有类似的问题,但我的问题完全不同,我还想再次检查一下我是否以最有效的方式(在资源方面)这样做。
我有已提交的调查,我想对结果进行统计。每个调查都保存在多维数组中,如下所示:
Array ( [name] => Clark Kent [rating] => 5 )
这些来自循环,因为它们是单独的数据库条目。
因此,我首先创建一个将所有这些结合在一起的新数组:
$mods = array();
$index = -1;
foreach($fields as $field) {
$index++;
$mods[$index]['name'] = $field['name'];
$mods[$index]['rating'] = $field['rating'];
}
然后我将它们分组,以使同一名称的所有评分都在一起,以便稍后进行总结。
$groups = array();
foreach ($mods as $value) {
$groups[$value['name']][] = $value;
}
这将产生以下结果:
Array (
[Clark Kent] => Array (
[0] => Array (
[name] => Clark Kent
[rating] => 5
)
[1] => Array (
[name] => Clark Kent
[rating] => 5
)
)
[Peter Parker] => Array (
[0] => Array (
[name] => Peter Parker
[rating] => 5
)
[1] => Array (
[name] => Peter Parker
[rating] => 5
)
)
[Bruce Wayne] => Array (
[0] => Array (
[name] => Bruce Wayne
[rating] => 5
)
[1] => Array (
[name] => Bruce Wayne
[rating] => 5
)
)
[Bruce Banner] => Array (
[0] => Array (
[name] => Bruce Banner
[rating] => 5
)
[1] => Array (
[name] => Bruce Banner
[rating] => 5
)
)
)
我要完成的工作是这样的:
<table>
<tr>
<td>Clark Kent</td>
<td>{average of all ratings}</td>
</tr>
</table>
我大部分时间都在那儿,但是我被困住了!我不确定如何获取没有任何索引或键类型的分组name
,因此我可以将该值用于表。然后,我需要对每个分组的值求和。
答案 0 :(得分:3)
要获得平均水平,您可以执行以下操作:
foreach ($groups as $name => $group) {
$average = array_sum(array_column($group, 'rating')) / count($group);
echo $name;
}
答案 1 :(得分:3)
我将在从数据库读取数据的循环中进行所有必要的数学运算。像这样:
$ratings = array();
while ($row = $result->fetch_assoc()) {
$name = $row['name'];
if (!isset($ratings[$name])) {
$ratings[$name] = array('count' => 1, 'sum' => $row['rating']);
}
else {
$ratings[$name]['count']++;
$ratings[$name]['sum'] += $row['rating'];
}
}
然后您可以像这样输出表:
echo "<table>";
foreach ($ratings as $name => $r) {
echo "<tr><td>$name</td><td>" . round($r['sum'] / $r['count'], 1) . "</td></tr>";
}
echo "</table>";
答案 2 :(得分:3)
您可以首先在用来处理这些日期的结构中简化问题
foreach($fields as $field) {
$mods[$field['name']][] = $field['rating'];
}
然后仅使用key参数进行
foreach($mods as $name => $mod) {
echo $name;
echo array_sum($mod) / count($mod);
}
答案 3 :(得分:2)
尝试使用下面的代码。消除了准备组数组的额外循环。
// we create new `LinkedList` as a backing queue and decorate it
ListenableQueue<String> q = new ListenableQueue<>(new LinkedList<>());
// register a listener which polls a queue and prints an element
q.registerListener(e -> System.out.println(q.poll()));
// voila!
q.add("record1");