Add AbstractCollection::flatten() method

This commit is contained in:
Giuseppe Criscione 2024-09-14 15:26:33 +02:00
parent e5918ffc9e
commit 6aac0fa0f4
2 changed files with 53 additions and 0 deletions

View File

@ -386,6 +386,16 @@ abstract class AbstractCollection implements Arrayable, Countable, Iterator
return Arr::pluck($this->data, $key, $default);
}
/**
* Flatten the collection items up to the specified depth
*/
public function flatten(int $depth = PHP_INT_MAX): static
{
$collection = $this->clone();
$collection->data = Arr::flatten($collection->data, $depth);
return $collection;
}
/**
* Filter the collection using the key from each item
*/

View File

@ -436,6 +436,49 @@ class Arr
return $result;
}
/**
* Flatten array items up to the specified depth
*
* @param array<mixed> $array
*
* @return array<mixed>
*/
public static function flatten(array $array, int $depth = PHP_INT_MAX): array
{
if ($depth === 0) {
return $array;
}
if ($depth < 0) {
throw new UnexpectedValueException(sprintf('%s() expects a non-negative depth', __METHOD__));
}
$result = [];
foreach ($array as $value) {
if ($value instanceof Arrayable) {
$value = $value->toArray();
}
if ($value instanceof Traversable) {
$value = iterator_to_array($value);
}
if (!is_array($value)) {
$result[] = $value;
continue;
}
if ($depth > 1) {
$value = static::flatten($value, $depth - 1);
}
foreach ($value as $val) {
$result[] = $val;
}
}
return $result;
}
/**
* Sort an array with the given options
*