Skip to content

Commit 9f53aeb

Browse files
committed
fix: bug Arr::flatten
1 parent d29a15b commit 9f53aeb

2 files changed

Lines changed: 28 additions & 2 deletions

File tree

Iterable/Arr.php

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,32 @@ public static function first(iterable $array, ?callable $callback = null, mixed
554554
return Helpers::value($default);
555555
}
556556

557+
/**
558+
* Flatten a multi-dimensional array into a single level.
559+
*/
560+
public static function flatten(array $array, float|int $depth = INF): array
561+
{
562+
$result = [];
563+
564+
foreach ($array as $item) {
565+
$item = $item instanceof Collection ? $item->all() : $item;
566+
567+
if (! is_array($item)) {
568+
$result[] = $item;
569+
} else {
570+
$values = $depth === 1
571+
? array_values($item)
572+
: static::flatten($item, $depth - 1);
573+
574+
foreach ($values as $value) {
575+
$result[] = $value;
576+
}
577+
}
578+
}
579+
580+
return $result;
581+
}
582+
557583
/**
558584
* Collapses a multi-dimensional array into a single dimension, using a delimited array path for
559585
* each array element's key, i.e. array(array('Foo' => array('Bar' => 'Far'))) becomes
@@ -564,7 +590,7 @@ public static function first(iterable $array, ?callable $callback = null, mixed
564590
*
565591
* @credit http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::flatten
566592
*/
567-
public static function flatten(array $data, string $separator = '.'): array
593+
public static function flattenSeparator(array $data, string $separator = '.'): array
568594
{
569595
$result = [];
570596
$stack = [];

Iterable/Collection.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ public function first(?callable $callback = null, $default = null)
360360
/**
361361
* {@inheritDoc}
362362
*/
363-
public function flatten(int $depth = INF)
363+
public function flatten(float|int $depth = INF)
364364
{
365365
return new static(Arr::flatten($this->items, $depth));
366366
}

0 commit comments

Comments
 (0)