合并两个大小相等的平面索引数组,以便将值以交替方式推入结果中

2021-12-27 00:00:00 merge arrays php alternating

假设我有两个数组:

$a1 = array(0, 1, 2);
$a2 = array(3, 4, 5);

我希望能够使用一种合并技术来交替数组值,而不仅仅是连接它们.我想要这个结果:

I want to be able to do a merge technique that alternates the array values and not just concatenate them. I want this result:

array(0, 3, 1, 4, 2, 5);

是否有一种本地方法可以做到这一点,因为这里的性能是一个问题,因为我需要这样做数千次

Is there a native way to do this as performance is an issue here since I need to do this thousands of times

请注意,我知道我可以这样做:

Please note, I know I can do it like this:

for (var $i = 0; $i < count($a1); $i++) {
    newArray[] = $a1[$i];
    newArray[] = $b1[$i];
}

如果有更快的方法,我正在寻找一种内置方法.

I'm looking for a built in way if there is a faster one.

推荐答案

$count = count($a1);
for ($i = 0; $i < $count; $i++) {
    $newArray[] = $a1[$i];
    $newArray[] = $b1[$i];
}

我在这里的工作已经完成.

My work here is done.

$a1 = array(0,1,2);
$a2 = array(3,4,5);

$start = microtime(TRUE);

for($t = 0; $t < 100000; $t++)
{
    $newArray = array();
    $count = count($a1);
    for ($i = 0; $i < $count; $i++)
    {
        $newArray[] = $a1[$i];
        $newArray[] = $a2[$i];
    }
}
echo  round(microtime(TRUE) - $start, 2); # 0.6

$a1 = array(0,1,2);
$a2 = array(3,4,5);

$start = microtime(TRUE);

for($t = 0; $t < 100000; $t++)
{
    $newArray = array();
    for ($i = 0; $i < count($a1); $i++)
    {
        $newArray[] = $a1[$i];
        $newArray[] = $a2[$i];
    }
}
echo  round(microtime(TRUE) - $start, 2); # 0.85

因此,预先计算的数组大小将是 ~1/4 [需要引用](在 100.000 次迭代中,您总共将获得 0.2)更快.如果将 count() 放入循环中,它将在每次 iteration 上重新计数.1/4 在我看来是相当快的.如果你正在寻找编译函数,你可以停止.

So pre-counting array size will be ~1/4 [citation needed] (on freakin' 100.000 iterations you will gain 0.2 in total) faster. If you put count() inside loop, it will recount on every iteration. 1/4 seems to me a reasonably faster. If you are looking for compiled function, you can stop.

附言Benchmark 就像比基尼,它向你展示了一切,什么都没有.

P.S. Benchmark is like bikini, it shows you everything, and nothing.

相关文章