首頁  >  文章  >  後端開發  >  PHP如何實現統計資料合併

PHP如何實現統計資料合併

little bottle
little bottle轉載
2019-04-25 13:55:043419瀏覽

這篇文章主要講述的是用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刪除