rikudou/iterables

提供了一些酷炫的可迭代函数,以补充内置的数组函数

v1.0.1 2024-07-20 22:11 UTC

This package is auto-updated.

Last update: 2024-09-20 22:43:20 UTC


README

一套简单的函数,重新实现了现有的php数组函数,但使用生成器来尽可能少地使用内存,并接受任何可迭代对象,而不仅仅是数组。

所以,这两个是等价的

<?php

use Rikudou\Iterables\Iterables;

$array = [1, 2, 3];

// built-in array_map
$mapped = array_map(fn (int $number) => $number ** 2, $array);
foreach ($mapped as $number) {
    echo $number, PHP_EOL;
}

$mapped = Iterables::map(fn (int $number) => $number ** 2, $array);
foreach ($mapped as $number) {
    echo $number, PHP_EOL;
}

差异主要在于其他可迭代对象

<?php

use Rikudou\Iterables\Iterables;

// an iterable generator
$generator = function () {
    yield 1;
    yield 2;
    yield 3;
};

// array_map only works with an array, so we need to convert it to array first
$mapped = array_map(fn (int $number) => $number ** 2, iterator_to_array($generator()));

// the library version works directly with iterables
$mapped = Iterables::map(fn (int $number) => $number ** 2, $generator());

在上面的例子中,实际上并没有太大的区别(除了你可以直接从返回迭代器的函数中获取结果,避免不必要的代码),但想象一下,有十亿行而不是三行。并且想象它是一个来自数据库的复杂对象,而不是整数。

请注意,有些函数需要遍历整个可迭代对象,因此你不会获得任何内存优势,但你仍然可以直接将任何可迭代对象输入其中,这是很棒的。

函数列表

  • Iterables::map() -> array_map()
  • Iterables::filter() -> array_filter()
  • Iterables::diff() -> array_diff()
  • Iterables::contains() -> in_array() - 与内置版本不同,这个默认是严格的
  • Iterables::firstValue() -> 等同于 $array[array_key_first($array)]
  • Iterables::count() -> count()
  • Iterables::find() -> array_find()
  • Iterables::findKey() -> array_find_key()
  • Iterables::any() -> array_any()
  • Iterables::all() -> array_all()