首页 >后端开发 >php教程 >PHP如何实现统计数据合并

PHP如何实现统计数据合并

little bottle
little bottle转载
2019-04-25 13:55:043476浏览

本篇文章主要讲述的是用PHP实现将不同的统计结果整合在一起,如图,根据年级统计出不同成绩段人数(此处只为举例),然后写了一个方法来处理这些统计数组,感兴趣的朋友可以去看看,希望对你有所帮助。

<?php

/**
 * 合并统计数据
 * @param $key_column         string  统计参照字段名
 * @param $_list_column       array 统计内容字段 统计字段默认值0
 * @param mixed ...$_list_arr array 需合并统计内容
 * @return array
 */
function statArrMergeHandle($key_column, $_list_column, ...$_list_arr)
{
  //整理统计参照字段内容
  $_total_key = array();
  foreach ($_list_arr as $_arr) $_total_key = array_merge($_total_key, array_column($_arr, $key_column));
  $_total_key = array_unique($_total_key);
  sort($_total_key);


  $_return_data = array();

  //组合返回数组统计字段及内容,默认值0(根据情况自行设置默认值)
  $_modal_key = array();
  foreach ($_list_column as $_column) $_modal_key[$_column] = 0;

  foreach ($_total_key as $key => $item) {
    $_arr_key = $_modal_key;
    $_arr_key[$key_column] = $item;

    foreach ($_list_arr as $_arr) {//遍历需合并数据结果
      foreach ($_arr as $em) {
        if ($item == $em[$key_column]) {
          foreach ($_list_column as $_column) {

            //统计结果大于0,更新相应统计字段数据(判断数组内容是否存在)
            if ($em[$_column] > 0) $_arr_key[$_column] = $em[$_column];
          }
        }
      }
    }
    $_return_data[$key] = $_arr_key;
    unset($_arr_key);
  }

  return $_return_data;
}


$score_a = array(
  array(&#39;grade&#39; => &#39;一年级&#39;, &#39;sum_a&#39; => 20),
  array(&#39;grade&#39; => &#39;二年级&#39;, &#39;sum_a&#39; => 21),
  array(&#39;grade&#39; => &#39;三年级&#39;, &#39;sum_a&#39; => 15),
  array(&#39;grade&#39; => &#39;四年级&#39;, &#39;sum_a&#39; => 3),
  array(&#39;grade&#39; => &#39;五年级&#39;, &#39;sum_a&#39; => 14)
);

$score_b = array(
  array(&#39;grade&#39; => &#39;一年级&#39;, &#39;sum_b&#39; => 21),
  array(&#39;grade&#39; => &#39;二年级&#39;, &#39;sum_b&#39; => 14),
  array(&#39;grade&#39; => &#39;四年级&#39;, &#39;sum_b&#39; => 40),
  array(&#39;grade&#39; => &#39;五年级&#39;, &#39;sum_b&#39; => 12),
  array(&#39;grade&#39; => &#39;六年级&#39;, &#39;sum_b&#39; => 25),
);

$score_c = array(
  array(&#39;grade&#39; => &#39;一年级&#39;, &#39;sum_c&#39; => 45),
  array(&#39;grade&#39; => &#39;三年级&#39;, &#39;sum_c&#39; => 24),
  array(&#39;grade&#39; => &#39;四年级&#39;, &#39;sum_c&#39; => 5),
  array(&#39;grade&#39; => &#39;六年级&#39;, &#39;sum_c&#39; => 12)
);

$score_d = array(
  array(&#39;grade&#39; => &#39;一年级&#39;, &#39;sum_d&#39; => 12),
  array(&#39;grade&#39; => &#39;二年级&#39;, &#39;sum_d&#39; => 45),
  array(&#39;grade&#39; => &#39;六年级&#39;, &#39;sum_d&#39; => 12)
);

$_last_data = statArrMergeHandle(&#39;grade&#39;, array(&#39;sum_a&#39;, &#39;sum_b&#39;, &#39;sum_c&#39;, &#39;sum_d&#39;), $score_a, $score_b, $score_c, $score_d);

最终结果:

相关教程:PHP视频教程

 

以上是PHP如何实现统计数据合并的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:cnblogs.com。如有侵权,请联系admin@php.cn删除