diff --git a/src/ArrayUtils.php b/src/ArrayUtils.php index 17e3ae3cd..b3006a3bb 100644 --- a/src/ArrayUtils.php +++ b/src/ArrayUtils.php @@ -9,6 +9,8 @@ namespace Zend\Stdlib; +use RecursiveArrayIterator; +use RecursiveIteratorIterator; use Traversable; use Zend\Stdlib\ArrayUtils\MergeRemoveKey; use Zend\Stdlib\ArrayUtils\MergeReplaceKeyInterface; @@ -332,4 +334,17 @@ public static function filter(array $data, $callback, $flag = null) return $output; } + + /** + * Flatten an array. + * + * Keys will be removed. Values will be kept in a single dimension array. + * + * @param array $data + * @return array + */ + public static function flatten(array $data) + { + return iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($data), RecursiveIteratorIterator::LEAVES_ONLY), false); + } } diff --git a/test/ArrayUtilsTest.php b/test/ArrayUtilsTest.php index 8127276fe..2b39e6104 100644 --- a/test/ArrayUtilsTest.php +++ b/test/ArrayUtilsTest.php @@ -527,6 +527,28 @@ function ($key) { ]; } + public function flattenArrays() + { + return [ + [ + ['bar', 'buz'], + ['bar', 'buz'] + ], + [ + ['foo' => 'bar', 'fiz' => 'buz'], + ['bar', 'buz'] + ], + [ + ['foo' => ['bar', 'fiz' => 'buz']], + ['bar', 'buz'] + ], + [ + ['foo' => ['blah' => ['eh' => 'bar'], 'fiz' => 'buz']], + ['bar', 'buz'] + ], + ]; + } + /** * @dataProvider filterArrays */ @@ -542,4 +564,13 @@ public function testInvalidCallableRaiseInvalidArgumentException() { ArrayUtils::filter([], "INVALID"); } + + + /** + * @dataProvider flattenArrays + */ + public function testFlattenArray($input, $expected) + { + $this->assertEquals($expected, ArrayUtils::flatten($input)); + } }