PHP数据集合与迭代器模式集合和迭代器用于统一处理数据集合。PHP的SPL提供了多种迭代器实现。今天说说PHP中集合和迭代器的用法。PHP的Iterator接口提供了遍历集合的标准方式。phpclass FileLineIterator implements Iterator{private $handle;private int $key 0;private ?string $current null;public function __construct(private string $path){$this-handle fopen($path, r);if ($this-handle false) throw new RuntimeException(无法打开文件: $path);$this-next();}public function current(): mixed { return $this-current; }public function key(): mixed { return $this-key; }public function next(): void{if (!feof($this-handle)) {$this-current fgets($this-handle);$this-key;} else {$this-current null;}}public function rewind(): void{rewind($this-handle);$this-key 0;$this-next();}public function valid(): bool{return $this-current ! false $this-current ! null;}public function __destruct(){if ($this-handle) fclose($this-handle);}}file_put_contents(/tmp/data.txt, 行1\n行2\n行3\n);foreach (new FileLineIterator(/tmp/data.txt) as $lineNum $line) {echo {$lineNum}: . trim($line) . \n;}?PHP的集合类封装了数组操作。phpclass Collection{private array $items [];public function __construct(array $items []){$this-items $items;}public function add(mixed $item): void{$this-items[] $item;}public function map(callable $callback): self{return new self(array_map($callback, $this-items));}public function filter(callable $callback): self{return new self(array_values(array_filter($this-items, $callback)));}public function reduce(callable $callback, mixed $initial null): mixed{return array_reduce($this-items, $callback, $initial);}public function first(): mixed{return !empty($this-items) ? $this-items[0] : null;}public function last(): mixed{return !empty($this-items) ? $this-items[count($this-items) - 1] : null;}public function count(): int{return count($this-items);}public function toArray(): array{return $this-items;}public function isEmpty(): bool{return empty($this-items);}public function chunk(int $size): array{$chunks [];foreach (array_chunk($this-items, $size) as $chunk) {$chunks[] new self($chunk);}return $chunks;}}$collection new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);$result $collection-filter(fn($v) $v % 2 0)-map(fn($v) $v * $v);print_r($result-toArray());echo 总数: . $result-count() . \n;?SPL提供的迭代器类。php// 递归目录迭代器$files new RecursiveIteratorIterator(new RecursiveDirectoryIterator(/tmp));foreach ($files as $file) {if ($file-isFile()) {echo $file-getPathname() . ( . $file-getSize() . 字节)\n;}}// 数组迭代器$iterator new ArrayIterator([a 1, b 2, c 3]);foreach ($iterator as $key $value) {echo $key $value\n;}// 过滤迭代器$filtered new CallbackFilterIterator(new ArrayIterator([1, 2, 3, 4, 5]),fn($v) $v % 2 0);foreach ($filtered as $v) echo $v ;echo \n;?Iterator和Collection模式让数据集合的处理更加统一。无论是数组、文件还是数据库结果集都可以用统一的接口遍历。SPL提供了丰富的迭代器类可以处理各种数据结构。