PHP数据集合与迭代器模式
集合和迭代器用于统一处理数据集合。PHP的SPL提供了多种迭代器实现。今天说说PHP中集合和迭代器的用法。
PHP的Iterator接口提供了遍历集合的标准方式。
```php
class 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的集合类封装了数组操作。
```php
class 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提供了丰富的迭代器类,可以处理各种数据结构。
PHP数据集合与迭代器模式
张小明
前端开发工程师
钢结构防火涂料工程施工验收规范(国家标准)
钢结构防火涂料工程施工验收规范(国家标准) 刮削方法:采用金属或非金属刮刀,如硬胶板刮刀、玻璃钢刮刀、牛角刮刀等手工刮刀,用于涂刷各种厚浆防火涂料和腻子。 辊涂法:辊筒为直径较小的中空圆筒,表面覆以合成纤维制成的长绒毛。气缸两端装有两个垫圈,中间有孔。弯曲的…
Joy-Con Toolkit完整指南:如何免费定制你的Switch手柄终极体验
Joy-Con Toolkit完整指南:如何免费定制你的Switch手柄终极体验 【免费下载链接】jc_toolkit Joy-Con Toolkit 项目地址: https://gitcode.com/gh_mirrors/jc/jc_toolkit 你是否厌倦了千篇一律的Switch手柄颜色?是否经常遇到摇杆漂移却束手无策&am…
AI 情感陪伴产品开发:对话设计与情感建模
AI 情感陪伴产品开发:对话设计与情感建模一、情感 AI 的本质:理解而非应答 当我们谈论 AI 情感陪伴时,首先要明确一个前提:AI 不是人,也不应该假装是人。真正有价值的情感 AI,不是让用户忘记他们是在和一个…
别急着删缓存!遇到conda的InvalidArchiveError,先试试这三步排查法(附conda clean详解)
别急着删缓存!遇到conda的InvalidArchiveError,先试试这三步排查法(附conda clean详解)在数据科学和Python开发领域,conda作为包管理和环境管理的利器,几乎成为每位开发者的标配工具。然而,当遇…
星露谷物语SMAPI完整指南:从零开始掌握模组加载与管理的终极教程
星露谷物语SMAPI完整指南:从零开始掌握模组加载与管理的终极教程 【免费下载链接】SMAPI The modding API for Stardew Valley. 项目地址: https://gitcode.com/gh_mirrors/smap/SMAPI 你是否曾经因为星露谷物语模组安装复杂、兼容性问题频发而感到困扰&…
芯片结温(Tj)详解:从热阻模型到散热设计实战
1. 芯片热设计的核心:深入理解结温(Tj)在硬件工程师的日常工作中,无论是调试一块新设计的FPGA核心板,还是为一个高功率的汽车MCU设计散热方案,有一个参数总是如影随形,却又常常被新手工程师所忽…