PHP集合管道与数据处理流程

集合管道是一种数据处理方式。多个操作串联起来处理数据集合。今天说说PHP中集合管道的实现。

简单的集合类。

```php
class Collection
{
private array $items;

public function __construct(array $items = [])
{
$this->items = $items;
}

public function map(callable $fn): self
{
return new self(array_map($fn, $this->items));
}

public function filter(callable $predicate): self
{
return new self(array_values(array_filter($this->items, $predicate)));
}

public function reduce(callable $fn, mixed $initial = null): mixed
{
return array_reduce($this->items, $fn, $initial);
}

public function each(callable $fn): self
{
foreach ($this->items as $key => $value) {
$fn($value, $key);
}
return $this;
}

public function first(): mixed
{
return $this->items[0] ?? null;
}

public function last(): mixed
{
return !empty($this->items) ? $this->items[count($this->items) - 1] : null;
}

public function sort(callable $callback = null): self
{
$items = $this->items;
if ($callback) {
usort($items, $callback);
} else {
sort($items);
}
return new self($items);
}

public function groupBy(string $key): self
{
$grouped = [];
foreach ($this->items as $item) {
$grouped[$item[$key]][] = $item;
}
return new self($grouped);
}

public function pluck(string $key): self
{
return new self(array_column($this->items, $key));
}

public function unique(string $key = null): self
{
if ($key) {
$seen = [];
$result = [];
foreach ($this->items as $item) {
$value = $item[$key] ?? null;
if (!in_array($value, $seen)) {
$seen[] = $value;
$result[] = $item;
}
}
return new self($result);
}
return new self(array_unique($this->items));
}

public function take(int $count): self
{
return new self(array_slice($this->items, 0, $count));
}

public function skip(int $count): self
{
return new self(array_slice($this->items, $count));
}

public function count(): int
{
return count($this->items);
}

public function toArray(): array
{
return $this->items;
}
}

$orders = new Collection([
['id' => 1, 'amount' => 100, 'status' => 'paid', 'user' => '张三'],
['id' => 2, 'amount' => 250, 'status' => 'pending', 'user' => '李四'],
['id' => 3, 'amount' => 80, 'status' => 'paid', 'user' => '王五'],
['id' => 4, 'amount' => 450, 'status' => 'cancelled', 'user' => '张三'],
['id' => 5, 'amount' => 200, 'status' => 'paid', 'user' => '李四'],
]);

$result = $orders
->filter(fn($o) => $o['status'] === 'paid')
->map(fn($o) => array_merge($o, ['final_amount' => $o['amount'] * 0.95]))
->sort(fn($a, $b) => $b['final_amount'] <=> $a['final_amount'])
->take(3);

print_r($result->toArray());

$stats = $orders
->groupBy('user')
->map(fn($userOrders) => [
'user' => $userOrders[0]['user'],
'total' => array_sum(array_column($userOrders, 'amount')),
'count' => count($userOrders),
]);

print_r($stats->toArray());
?>

管道风格的数据处理。

```php
$pipeline = $orders
->filter(fn($o) => $o['status'] !== 'cancelled')
->map(fn($o) => $o['amount'])
->reduce(fn($c, $v) => $c + $v, 0);

echo "有效订单总额: $pipeline\n";

$userSummary = $orders
->filter(fn($o) => $o['status'] === 'paid')
->groupBy('user')
->map(fn($orders, $user) => [
'user' => $orders[0]['user'],
'total' => array_sum(array_column($orders, 'amount')),
'orders' => count($orders),
])
->sort(fn($a, $b) => $b['total'] <=> $a['total']);

print_r($userSummary->toArray());
?>

集合管道让数据处理更清晰。每个操作返回新的集合,多个操作可以链式调用。map转换元素,filter过滤元素,reduce归约元素。groupBy分组统计,sort排序。集合管道让数据处理代码更有表达力。

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐