'名字','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); // 获取字段指向 $fields = array_keys($this->fields); $newList = []; foreach ($this->data as $info) { $temp = []; foreach ($fields as $field) { if ($field == 'idcard') { $temp[$field] = ' ' . $this->getDotValue($info, $field); } else { $temp[$field] = $this->getDotValue($info, $field); } } $newList[] = $temp; } 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; } }