<?php
$input = [
'a',
['b', 'c'],
'd', ['e'], ['f', 'g'],
['h', 'i', ['j', ['k'], ['l', 'm', ['n']]]],
'o', 'p', ['q', 'r'], ['s', ['t', ['u', ['v']]]],
'w', 'x', 'y', 'z'];
class TraversableInput implements \IteratorAggregate
{
public $input = [
'a',
['b', 'c'],
'd', ['e'], ['f', 'g'],
['h', 'i', ['j', ['k'], ['l', 'm', ['n']]]],
'o', 'p', ['q', 'r'], ['s', ['t', ['u', ['v']]]],
'w', 'x', 'y', 'z'];
function getIterator()
{
return new ArrayIterator($this->input);
}
}
$input = new TraversableInput();
function flatten1($input) {
return \array_reduce(
(array) $input,
function ($carry, $item) {
return \is_array($item) ?
\array_merge($carry, flatten1($item)) :
\array_merge($carry, [$item]);
},
[]
);
}
function flatten2($input) {
$stack = [$input];
$result = [];
while (!empty($stack)) {
$item = array_shift($stack);
if (is_array($item) || $item instanceof Traversable) {
foreach ($item as $element) {
array_unshift($stack, $element);
}
} else {
array_unshift($result, $item);
}
}
return $result;
}
$start = microtime(TRUE);
for($x=0;$x<10000;$x++){
flatten1($input);
};
$end = microtime(TRUE);
$diff = $end-$start;
$sec = intval($diff);
$micro = $diff - $sec;
$final = strftime('%T', mktime(0, 0, $sec)) . str_replace('0.', '.', sprintf('%.10f', $micro));
echo "Flatten1: " . $final . "\n";
$start = microtime(TRUE);
for($x=0;$x<10000;$x++){
flatten2($input);
};
$end = microtime(TRUE);
$diff = $end-$start;
$sec = intval($diff);
$micro = $diff - $sec;
$final = strftime('%T', mktime(0, 0, $sec)) . str_replace('0.', '.', sprintf('%.10f', $micro));
echo "Flatten2: " . $final . "\n";
preferences:
23.65 ms | 413 KiB | 5 Q