問題描述
假設我有兩個數組:
$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.
這篇關于合并兩個大小相等的平面索引數組,以便將值以交替方式推入結果中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!