合并所有其他数组php [英] Merge every other array php
问题描述
数组1: 1,3,5,7
数组2: 2,4,6,8
我想要的数组为 1,2,3,4,5,6,7,8
我只是以数字为例。如果只是数字,我可以合并和排序,但它们将是单词。所以也许像
I'm just using numbers as examples. If it was just numbers i could merge and sort but they will be words. So maybe something like
数组一: bob,a,awesome
第二个数组:确实是花花公子
应读为: bob是个很棒的家伙
不知道该怎么做。 PHP是否内置了类似这样的东西?
Not really sure how to do this. Does PHP have something like this built in?
推荐答案
您可以编写如下函数:
function array_merge_alternating($array1, $array2) {
if(count($array1) != count($array2)) {
return false; // Arrays must be the same length
}
$mergedArray = array();
while(count($array1) > 0) {
$mergedArray[] = array_shift($array1);
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
此函数期望两个长度相等的数组并合并其值。
This function expects two arrays with equal length and merges their values.
如果不需要交替使用值,则可以使用 array_merge
。 array_merge
会将第二个数组附加到第一个数组,并且不会执行您所要求的操作。
If you don't need your values in alternating order you can use array_merge
. array_merge
will append the second array to the first and will not do what you ask.
这篇关于合并所有其他数组php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!