'名字','user.sex'=>'性别'] $this->fields = $exportFields; // 数据 $this->data = $data; } /** * 数组转集合 * @throws ErrorException */ public function collection() { if (empty($this->fields)) { throw new ErrorException('导出字段不能为空'); } if (!is_array($this->fields)) { throw new ErrorException('导出字段必须是数组'); } // 获取表头 $header = array_values($this->fields); $moreFileds = []; // 表头追加附属数据 if (isset($this->data[0]['data']) && is_array($this->data[0]['data'])) { $moreHeader = array_column($this->data[0]['data'], 'name'); // 获取头信息 $header = array_merge($header, $moreHeader); // 获取字段信息 $moreFileds = array_column($this->data[0]['data'], 'field'); } // 获取字段指向 $fields = array_keys($this->fields); $newList = []; foreach ($this->data as $info) { $temp = []; foreach ($fields as $field) { if (str_contains($field, 'idcard')) { $temp[$field] = ' ' . $this->getDotValue($info, $field); } elseif (str_contains($field, 'all_course')) { $temp[$field] = $this->allCourse($info); } else { $temp[$field] = $this->getDotValue($info, $field); } } // 如果有自定义数据,全部附件上去 $t2 = []; if (isset($info['data']) && $info['data'] && !empty($moreFileds)) { $dataCollect = collect($info['data']); foreach ($moreFileds as $moreFiled) { $value = ($dataCollect->where('field', $moreFiled)->first()['value']) ?? ''; if (str_contains($moreFiled, 'idcard')) { $t2[$moreFiled] = ' ' . $value; } else { $t2[$moreFiled] = $value; } } } $newList[] = $temp + $t2; } array_unshift($newList, $header); //插入表头 return new Collection($newList); } /** * .号转数组层级并返回对应的值 * @param $key * @param null $default * @return mixed|null */ function getDotValue($config, $key, $default = null) { // 如果在第一层,就直接返回 if (isset($config[$key])) { return $config[$key]; } // 如果找不到,直接返回默认值 if (false === strpos($key, '.')) { return $default; } // 临时数组 $tempArr = explode('.', $key); foreach ($tempArr as $segment) { if (!is_array($config) || !array_key_exists($segment, $config)) { return $default; } $config = $config[$segment]; } return $config; } /** * 获取所有课程名称 * @param $data */ function allCourse($data) { $list = []; foreach ($data['course_signs'] as $item) { $list[] = $item['course']['name'] ?? ''; } return implode("、\r\n", $list); } }