2021-12-09 22:41:22 +01:00
|
|
|
<?php
|
|
|
|
|
2021-12-09 23:22:12 +01:00
|
|
|
namespace trizz\AdventOfCode\Utils;
|
2021-12-09 22:41:22 +01:00
|
|
|
|
2022-11-29 19:52:02 +01:00
|
|
|
final class Arr
|
2021-12-09 22:41:22 +01:00
|
|
|
{
|
2021-12-09 23:22:12 +01:00
|
|
|
/**
|
|
|
|
* Flatten a multi-dimensional array into a single level.
|
|
|
|
*
|
|
|
|
* Based on:
|
|
|
|
*
|
|
|
|
* @see https://github.com/laravel/framework/blob/c16367a1af68d8f3a1addc1a819f9864334e2c66/src/Illuminate/Collections/Arr.php#L221-L249
|
|
|
|
*
|
2022-11-29 19:52:02 +01:00
|
|
|
* @param array<mixed> $array
|
2021-12-09 23:22:12 +01:00
|
|
|
*
|
2022-11-29 19:52:02 +01:00
|
|
|
* @return array<mixed>
|
2021-12-09 23:22:12 +01:00
|
|
|
*/
|
2022-11-29 19:52:02 +01:00
|
|
|
public static function flatten(iterable $array, float|int $depth = INF): array
|
2021-12-09 23:22:12 +01:00
|
|
|
{
|
|
|
|
$result = [];
|
2021-12-09 22:41:22 +01:00
|
|
|
|
2021-12-09 23:22:12 +01:00
|
|
|
foreach ($array as $item) {
|
|
|
|
if (!is_array($item)) {
|
|
|
|
$result[] = $item;
|
|
|
|
} else {
|
|
|
|
$values = $depth === 1
|
|
|
|
? array_values($item)
|
|
|
|
: static::flatten($item, $depth - 1);
|
|
|
|
|
|
|
|
foreach ($values as $value) {
|
|
|
|
$result[] = $value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $result;
|
|
|
|
}
|
2021-12-09 22:41:22 +01:00
|
|
|
}
|