Skip to content
This repository was archived by the owner on Jan 31, 2020. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/ArrayUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

namespace Zend\Stdlib;

use RecursiveArrayIterator;
use RecursiveIteratorIterator;
use Traversable;
use Zend\Stdlib\ArrayUtils\MergeRemoveKey;
use Zend\Stdlib\ArrayUtils\MergeReplaceKeyInterface;
Expand Down Expand Up @@ -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);
}
}
31 changes: 31 additions & 0 deletions test/ArrayUtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand All @@ -542,4 +564,13 @@ public function testInvalidCallableRaiseInvalidArgumentException()
{
ArrayUtils::filter([], "INVALID");
}


/**
* @dataProvider flattenArrays
*/
public function testFlattenArray($input, $expected)
{
$this->assertEquals($expected, ArrayUtils::flatten($input));
}
}