在 PHP 中按键和值对多维数组进行分组

我有提交的调查,我想统计结果。每个调查都保存在一个多维数组中,如下所示:


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没有任何类型的索引或键的分组,以便我可以将该值用于我的表。然后我需要对每个分组的值求和。


慕无忌1623718
浏览 204回答 3
3回答

拉莫斯之舞

我会在从数据库读取数据的循环中做所有必要的数学运算。像这样的东西:$ratings = array();while ($row = $result->fetch_assoc()) {&nbsp; &nbsp; $name = $row['name'];&nbsp; &nbsp; if (!isset($ratings[$name])) {&nbsp; &nbsp; &nbsp; &nbsp; $ratings[$name] = array('count' => 1, 'sum' => $row['rating']);&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; $ratings[$name]['count']++;&nbsp; &nbsp; &nbsp; &nbsp; $ratings[$name]['sum'] += $row['rating'];&nbsp; &nbsp; }}然后你可以像这样输出你的表格:echo "<table>";foreach ($ratings as $name => $r) {&nbsp; &nbsp; echo "<tr><td>$name</td><td>" . round($r['sum'] / $r['count'], 1) . "</td></tr>";}echo "</table>";

红糖糍粑

要获得平均值,您可以执行以下操作:foreach ($groups as $name => $group) {&nbsp; &nbsp; $average = array_sum(array_column($group, 'rating')) / count($group);&nbsp; &nbsp; echo $name;}

慕桂英4014372

您可以首先在用于处理这些日期的结构中简化问题foreach($fields as $field) {&nbsp; &nbsp; &nbsp;$mods[$field['name']][] = $field['rating'];}然后只用关键参数 foreachforeach($mods as $name => $mod) {&nbsp; &nbsp; &nbsp;echo $name;&nbsp; &nbsp; &nbsp;echo array_sum($mod) / count($mod);}
打开App,查看更多内容
随时随地看视频慕课网APP