public function census() { $data = $this->request->post("params/a"); // $data = [ // ['name' => 'Alice', 'specId' => 25], // ['name' => 'Bob', 'specId' => 25], // ['name' => 'Charlie', 'specId' => 26], // ['name' => 'Alice', 'specId' => 26], // ['name' => 'Bob', 'specId' => 26], // ]; // 按字段分组 $grouped = array_reduce($data, function ($carry, $item) { $carry[$item['specId']][] = $item; return $carry; }, []); // 计算每个分组的数量 $groupCounts = array_map(function ($group) { return count($group); }, $grouped); // print_r($groupCounts); // 使用array_column()获取特定字段,然后用array_unique()获取唯一值 $uniqueItems = array_values(array_unique(array_column($data, 'specId'), SORT_REGULAR)); // 使用array_filter()重新组装数组 $filteredArray = array_filter($data, function ($item) use ($uniqueItems) { static $found = []; if (in_array($item['specId'], $found)) { return false; // 如果已经找到,不包含在结果中 } else { $found[] = $item['specId']; // 标记为找到 return true; } }); // print_r($filteredArray);exit(); foreach($filteredArray as $key => $val) { if(isset($groupCounts[$val['specId']])) { $filteredArray[$key]['num'] = $groupCounts[$val['specId']]; } } $this->success('',$filteredArray); }