递归重新排序数组键 - array_slice慢?

时间:2017-02-11 16:41:41

标签: php arrays key

我写了一个方法来重新排序数组上的所有数字键。

你可以在下面的代码中看到我有一个带有未排序键的数组。 这个键(f.e. 200,2)应该递归地重新排序(f.e.,0,1)。 这应该在php 5.6中最多7个,但至少在7

完美无缺,但似乎很慢。 我想知道是否有人知道如何更快地获得这个。

代码和测试:

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;

感谢您的帮助! / cottton

1 个答案:

答案 0 :(得分:0)

方式去(直到有人有更好的解决方案) 每个阵列级别都是array_merge

function reorderKeysRecursively(array &$array)
{
    foreach ($array as $key => &$value) {
        if (is_array($value)) {
            $array[$key] = reorderKeysRecursively($value);
        }
    }
    return array_merge($array);
}

停止

[
    0 => [                  // before: 2
        'foo' => 'bar',
        0     => 'baz',     // before: 2
        'bar' => 3,
        1     => [          // before: 33
            0 => [          // before: 55
                0 => [      // before: 2
                    0 => [  // before: 55
                        'foo' => 'bar',
                    ],
                ],
            ],
        ],
        'baz' => 4,
    ],
]