Created
October 23, 2018 13:11
-
-
Save m4s0/2209c9d7d65fca3574bca84472c50b28 to your computer and use it in GitHub Desktop.
recursively flatten a multidimensional array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ArrayFlat | |
{ | |
public function execute($arg): array | |
{ | |
return is_array($arg) ? array_reduce($arg, function ($c, $a) { | |
return array_merge($c, $this->execute($a)); | |
}, []) : [$arg]; | |
} | |
} | |
use PHPUnit\Framework\Assert; | |
use PHPUnit\Framework\TestCase; | |
class ArrayFlatTest extends TestCase | |
{ | |
/** | |
* @test | |
*/ | |
public function i_should_be_able_to_flatten_a_multidimensional_array() | |
{ | |
$arrayFlat = new ArrayFlat(); | |
$flat = $arrayFlat->execute([[1, 2, [3]], 4]); | |
Assert::assertEquals([1, 2, 3, 4], $flat); | |
$flat = $arrayFlat->execute([1, 2, [3, 4, 5, 6], 7, 8, [9, 10, [11, 12]]]); | |
Assert::assertEquals([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], $flat); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment