Merge two flat indexed arrays of equal size so that values are pushed into the result in an alternating fashion(合并两个大小相等的平面索引数组,以便将值以交替方式推入结果中)
问题描述
假设我有两个数组:
$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.
这篇关于合并两个大小相等的平面索引数组,以便将值以交替方式推入结果中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:合并两个大小相等的平面索引数组,以便将值以交替方式推入结果中
基础教程推荐
- 使用 PDO 转义列名 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01