I wrote a method to reorder all numeric keys on an array.
You can see in code below that i have an array with unsorted keys. This keys (f.e. 200, 2) should be reordered (f.e. 0, 1) recursively. This should work in php 5.6 up to 7 but at least in 7
Perfectly works but seems very slow. I wonder if anybody knows how to get this faster.
Code and Test:
function reorderKeysRecursively(array $array)
{
foreach ($array as $key => &$value) {
if (is_array($value)) {
$array[$key] = reorderKeysRecursively($value);
}
}
return array_slice($array, 0);
}
$array = [
2 => [
'foo' => 'bar',
2 => 'baz',
'bar' => 3,
33 => [
55 => [
2 => [
55 => [
'foo' => 'bar'
],
],
],
],
'baz' => 4,
],
];
$start = microtime(true);
for ($i = 0; $i < 200000; $i++) {
reorderKeysRecursively($array);
}
echo "elapsed: " . (microtime(true) - $start) . PHP_EOL;
$expect = json_encode(
[
0 => [
'foo' => 'bar',
0 => 'baz',
'bar' => 3,
1 => [
0 => [
0 => [
0 => [
'foo' => 'bar',
],
],
],
],
'baz' => 4,
],
]
);
$result = json_encode(reorderKeysRecursively($array));
echo "is expected result: " . (var_export($result === $expect, true)) . PHP_EOL;
Thanks for helping! /cottton