mirror of
https://github.com/getformwork/formwork.git
synced 2025-01-18 05:58:20 +01:00
Add AbstractCollection::flatten()
method
This commit is contained in:
parent
e5918ffc9e
commit
6aac0fa0f4
@ -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
|
||||
*/
|
||||
|
@ -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
|
||||
*
|
||||
|
Loading…
x
Reference in New Issue
Block a user