<?php /** * Created by PhpStorm. * User: zhonglei * Date: 17/10/14 * Time: 16:12 */ namespace Apicp\Controller\CourseData; use Common\Common\Constant; use Common\Model\CourseClassModel; use Common\Model\CourseArticleModel; class ClassDataController extends \Apicp\Controller\AbstractController { /** * ClassData * @author zhonglei * @desc 课程分布情况报表接口 * @return array array( 'top' => array( // 一级分类数据 array( 'name' => '分类A', // 分类名称 'value' => 80, // 课程数 ), ), 'child' => array( // 二级分类数据 array( 'name' => '分类B', // 分类名称 'value' => 20, // 课程数 ), ), 'total' => 100, // 课程总数 ) */ public function Index_post() { $this->_result = [ 'top' => [], 'child' => [], 'total' => 0, ]; // 获取分类数据 $classModel = new CourseClassModel(); $class_list = $classModel->list_all(); if (empty($class_list)) { return; } $class_data = array_combine_by_key($class_list, 'class_id'); // 格式化分类数据 foreach ($class_data as $class_id => $class) { $class_data[$class['parent_id']]['children'][$class_id] = &$class_data[$class_id]; } // 一级分类ID数组 $top_ids = array_keys($class_data[0]['children']); // 二级分类ID数组 $child_ids = []; foreach ($top_ids as $top_id) { if (isset($class_data[$top_id]['children'])) { $child_ids = array_merge($child_ids, array_keys($class_data[$top_id]['children'])); } } $list = [ 'top' => $top_ids, 'child' => $child_ids, ]; // 获取课程分类包含课程门数数据 $articleModel = new CourseArticleModel(); $class_total_list = $articleModel->listClassData(['course_type' => Constant::COURSE_TYPE_NORMAL]); $class_totals = array_combine_by_key($class_total_list, 'class_id'); foreach ($list as $k => $class_ids) { // 遍历一级分类ID和二级分类ID foreach ($class_ids as $class_id) { $ids = []; $this->_getSelfChildId($class_data[$class_id], $ids); $total = 0; // 遍历自身ID和所有子分类ID,取出分类下课程总数 foreach ($ids as $id) { if (isset($class_totals[$id])) { $total += $class_totals[$id]['total']; } } $this->_result[$k][] = [ 'name' => $class_data[$class_id]['class_name'], 'value' => $total, ]; } } // 课程总数 $this->_result['total'] = array_sum(array_column($class_total_list, 'total')); } /** * 获取分类自身ID和所有子分类ID * @author zhonglei * @param array $class 分类数据 * @param array $ids 分类自身ID和所有子分类ID数组(引用) * @return void */ private function _getSelfChildId($class, &$ids) { $ids[] = $class['class_id']; // 包含子级分类 if (isset($class['children'])) { foreach ($class['children'] as $child) { $this->_getSelfChildId($child, $ids); } } } }