Skip to content

Instantly share code, notes, and snippets.

@liverbool
Last active May 14, 2020 08:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liverbool/4992b4dd9dce5e4088f1defbe1c989f0 to your computer and use it in GitHub Desktop.
Save liverbool/4992b4dd9dce5e4088f1defbe1c989f0 to your computer and use it in GitHub Desktop.
How to fast flatten array in php.
<?php
# Flatten array and modify it's value
# [[1, 2, 3, 4, [3, 4]] => [1, 2, 3, 4, 3, 4]
# php ./script.php to test
$total = 30000;
$mockData = [];
for($i = 1; $i < $total; $i++) {
$mockData[] = ['id' => $i, 'name' => 'sample' . $i];
}
$modifiers = [
function ($key, $value) { return $value; },
function ($key, $value) { if (1 === $value && 'id' === $key) { return 'changed'; } return $value; },
];
function print_result($title, \DateTime $time, $parameters, $sym) {
$end = $time->diff(new \DateTime());
echo \vsprintf('%s Time: %s:%s:%s:%s Size: %smb %s', [
$title,
$end->h, $end->i, $end->s, $end->f,
\strlen(\serialize($parameters)) * 0.000001,
$sym
]) . PHP_EOL;
}
## Method 1
$start = new \DateTime();
$data = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($mockData));
$parameters = [];
$data->rewind();
while ($data->valid()) {
$key = $data->key();
$value = $data->current();
\array_map(function ($modifier) use (&$value, $key) {
$value = \call_user_func($modifier, $key, $value);
}, $modifiers);
$parameters[] = $value;
$data->next();
}
print_result('#1', $start, $parameters, '🏎️');
# Method 2
$start = new \DateTime();
$parameters = \array_reduce($mockData, function (array $flattenedValues, array $valueSet) use ($modifiers) {
\array_map(function ($modifier) use (&$valueSet) {
\array_walk($valueSet, function (&$value, $key) use ($modifier) {
$value = \call_user_func($modifier, $key, $value);
});
}, $modifiers);
return \array_merge($flattenedValues, array_values($valueSet));
}, []);
print_result('#2', $start, $parameters, '🐢');
# Method 2x -- without modifier
$start = new \DateTime();
$parameters = \array_reduce($mockData, function (array $flattenedValues, array $valueSet) {
return \array_merge($flattenedValues, array_values($valueSet));
}, []);
print_result('#2x', $start, $parameters, '🐢');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment