Hard to put a descriptive title to this which is easy to understand so I will try in more depth here. Say I have 4 arrays of different sizes, a1, a2, a3 and a4 which I want to combine into the array SUM.
很难给这个东西加上一个描述性的标题,这很容易理解,所以我将在这里更深入地尝试。假设我有4个不同大小的数组,a1, a2, a3和a4我想把它们组合成数组和。
I want SUM[0] to be a1[0], SUM[1] to be a2[0], SUM[2] to be a3[0], SUM[3] to be a4[0] and then SUM[4] to be a1[1] and so on.
我想和a1[0][0],和a2[0][1],[2]和a3[0],[3]和a4[0]然后总和[4]是a1[1]等等。
A tricky thing to consider is the arrays are different sizes.
需要考虑的一件棘手的事情是数组的大小不同。
edit: if any array a1,a2,a3,a4 terminates, just move onto the next one - sorry for not making this clear
编辑:如果任何数组a1,a2,a3,a4终止,就移到下一个,抱歉没有说清楚。
1 个解决方案
#1
4
$a1=array(1,2,3);
$a2=array(4,5,6,7,8,9);
$a3=array(10,11);
$a4=array(12,13,14,15);
$maxlen = max(count($a1), count($a2), count($a3), count($a4));
$a = array($a1, $a2, $a3, $a4);
$SUM = array();
for ($i = 0; $i < $maxlen; $i++) {
foreach ($a as $arr) {
if (array_key_exists($i, $arr)) {
$SUM[] = $arr[$i];
}
}
}
var_dump($SUM);
OUTPUT:
输出:
array(15) { [0]=> int(1) [1]=> int(4) [2]=> int(10) [3]=> int(12) [4]=> int(2) [5]=> int(5) [6]=> int(11) [7]=> int(13) [8]=> int(3) [9]=> int(6) [10]=> int(14) [11]=> int(7) [12]=> int(15) [13]=> int(8) [14]=> int(9) }
数组(15){[0]= > int(1)[1]= > int(4)[2]= > int(10)[3]= > int(12)[4]= > int(2)[5]= > int(5)[6]= > int(11)[7]= > int(13)[8]= > int(3)[9]= > int(6)[10]= > int(14)[11]= > int(7)[12]= > int(15)[13]= > int(8)[14]= > int(9)}
#1
4
$a1=array(1,2,3);
$a2=array(4,5,6,7,8,9);
$a3=array(10,11);
$a4=array(12,13,14,15);
$maxlen = max(count($a1), count($a2), count($a3), count($a4));
$a = array($a1, $a2, $a3, $a4);
$SUM = array();
for ($i = 0; $i < $maxlen; $i++) {
foreach ($a as $arr) {
if (array_key_exists($i, $arr)) {
$SUM[] = $arr[$i];
}
}
}
var_dump($SUM);
OUTPUT:
输出:
array(15) { [0]=> int(1) [1]=> int(4) [2]=> int(10) [3]=> int(12) [4]=> int(2) [5]=> int(5) [6]=> int(11) [7]=> int(13) [8]=> int(3) [9]=> int(6) [10]=> int(14) [11]=> int(7) [12]=> int(15) [13]=> int(8) [14]=> int(9) }
数组(15){[0]= > int(1)[1]= > int(4)[2]= > int(10)[3]= > int(12)[4]= > int(2)[5]= > int(5)[6]= > int(11)[7]= > int(13)[8]= > int(3)[9]= > int(6)[10]= > int(14)[11]= > int(7)[12]= > int(15)[13]= > int(8)[14]= > int(9)}