JBZoo\Utils\Arr::flat PHP Method

flat() public static method

Flatten a multi-dimensional array into a one dimensional array.
public static flat ( array $array, boolean $preserve_keys = true ) : array
$array array The array to flatten
$preserve_keys boolean Whether or not to preserve array keys. Keys from deeply nested arrays will overwrite keys from shallowy nested arrays
return array
    public static function flat(array $array, $preserve_keys = true)
    {
        $flattened = array();
        array_walk_recursive($array, function ($value, $key) use(&$flattened, $preserve_keys) {
            if ($preserve_keys && !is_int($key)) {
                $flattened[$key] = $value;
            } else {
                $flattened[] = $value;
            }
        });
        return $flattened;
    }

Usage Example

Exemplo n.º 1
0
 public function testFlatten()
 {
     $input = array('a', 'b', 'c', 'd', array('first' => 'e', 'f', 'second' => 'g', array('h', 'third' => 'i', array(array(array(array('j', 'k', 'l')))))));
     $expectNoKeys = range('a', 'l');
     $expectWithKeys = array('a', 'b', 'c', 'd', 'first' => 'e', 'f', 'second' => 'g', 'h', 'third' => 'i', 'j', 'k', 'l');
     is($expectWithKeys, Arr::flat($input));
     is($expectNoKeys, Arr::flat($input, false));
     is($expectWithKeys, Arr::flat($input, true));
 }