合并两个数组的优雅方法是什么,这样得到的数组有两个来自第一个数组的项,后跟第二个数组中的一个项,以这种方式重复?
数组1 = A1,A2,A3,A4,A5等
数组2 = B1,B2,B3,B4,B5等
结果= A1,A2,B1,A3,A4,B2,A5,A6,B3等.
我正在尝试使用带有多个计数器的for循环来完成它,但我不知道数组长度总是根据需要长或短.我很好奇:有更好的方法吗?
这是我目前正在做的简化版本:
$x = 0, $y = 0;
for($i=0; $i<$total_num_blocks; $i++) {
if ($i % 3) { // if there's a remainder, it's not an 'every 3rd' item
$result[$i] = $projects[$x++];
} else {
$result[$i] = $posts[$y++];
}
}
Run Code Online (Sandbox Code Playgroud) 我需要将3个数组合并为1,同时按照第二个数组的第一个条目跟随第一个数组的第一个条目的方式对新数组进行排序.
例:
$array1 = array(dog, cat, mouse);
$array2 = array(table, chair, couch);
$array3 = array(car, bike, bus);
Run Code Online (Sandbox Code Playgroud)
这些数组应该产生以下数组:
$resultarray = array(dog, table, car, cat, chair, bike, mouse, couch, bus);
Run Code Online (Sandbox Code Playgroud)
非常感谢您的回复!
我要的是一个efficient(不循环)方式,该方式合并阵列first element of the resulting array是first element of the first array,the second element of the resulting array是the second element of the second array(或者)...等
例:
$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);
$resultingArray = array(1, 2, 3, 4, 5, 6);
Run Code Online (Sandbox Code Playgroud)