合并两个数组,合并排序样式 [英] merge two arrays, merge-sort style

查看:83
本文介绍了合并两个数组,合并排序样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个数组:

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

我希望能够进行合并,使数组交替而不是合并.我想要这个结果:

I want to be able to do a merge that alternates the arrays and not concatanate 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 [需要引用](在freakin的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.

P.S.基准就像比基尼一样,它可以显示所有内容,而没有任何显示.

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

这篇关于合并两个数组,合并排序样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆