Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

php - Merge two flat indexed arrays of equal size so that values are pushed into the result in an alternating fashion

Suppose I have two arrays:

$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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$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

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. Benchmark is like bikini, it shows you everything, and nothing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...