将从foreach循环中输出2个或更多数组。喜欢以下
array1
[0] => Array
(
[0] => 1207
[1] => 4
[2] => haha.mp4
)
[1] => Array
(
[0] => 1208
[1] => 4
[2] => hehe.mp4
)
array2
[0] => Array
(
[0] => 1209
[1] => 16
[2] => SampleVideo.mp4
)
[1] => Array
(
[0] => 1210
[1] => 16
[2] => 295.mp4
)
我想从这两个数组中获取相同的索引值并合并这些数组。
**FinalArray = array1[0],array2[0],array1[1],array2[1]**
E.g
FinalArray
[0] => Array
(
[0] => 1207
[1] => 4
[2] => haha.mp4
)
[1] => Array
(
[0] => 1209
[1] => 16
[2] => SampleVideo.mp4
)
[2] => Array
(
[0] => 1208
[1] => 4
[2] => hehe.mp4
)
[3] => Array
(
[0] => 1210
[1] => 16
[2] => 295.mp4
)
请帮助如何获取相同的索引值并合并该2个数组。感谢
答案 0 :(得分:1)
您可以使用array_column和array_merge进行一次循环来实现此目的,如下所示,
$array1 = array(
0 => [0 => 1207, 1 => 4, 2 => "haha.mp4"],
1 => [0 => 1208, 1 => 4, 2 => "hehe.mp4"],
);
$array2 = array(
0 => [0 => 1209, 1 => 16, 2 => "SampleVideo.mp4"],
1 => [0 => 1210, 1 => 16, 2 => "295.mp4"],
);
// here I assume that the following array is the output of your foreach loop
$array = [$array1, $array2];
$list = [];
foreach ($array as $key => $value) {
$list = array_merge($list, array_column($array, $key));
}
print_r($list);
答案 1 :(得分:0)
代码:(Demo)
$array1 = array(
0 => [0 => 1207, 1 => 4, 2 => "haha.mp4"],
1 => [0 => 1208, 1 => 4, 2 => "hehe.mp4"],
);
$array2 = array(
0 => [0 => 1209, 1 => 16, 2 => "SampleVideo.mp4"],
1 => [0 => 1210, 1 => 16, 2 => "295.mp4"],
);
foreach($array1 as $k=>$v){
$result[]=$v;
// if $array2 always has a matching key:
$result[]=$array2[$k];
// if it is possible that $array2 doesn't have a matching key:
// if(isset($array2[$k]){$result[]=$array2[$k];}
//... if you have more arrays to include, just repeat like: $result[]=$array3[$k];
}
var_export($result);
输出:
array (
0 =>
array (
0 => 1207,
1 => 4,
2 => 'haha.mp4',
),
1 =>
array (
0 => 1209,
1 => 16,
2 => 'SampleVideo.mp4',
),
2 =>
array (
0 => 1208,
1 => 4,
2 => 'hehe.mp4',
),
3 =>
array (
0 => 1210,
1 => 16,
2 => '295.mp4',
),
)
答案 2 :(得分:-1)
$result = array_merge($array1, $array2);
print_r($result);
答案 3 :(得分:-1)
要获得带有元素顺序array0[0],array1[0],array0[1],array1[1]
的finalArray,首先计算$max_elements
,然后执行嵌套循环,检查该数组中是否存在$i
元素:
$arrays = [$array0, $array1];
$max_elements = 0;
foreach($arrays as $array){
$max_elements = max($max_elements, count($array));
}
$merged = []
for($i = 0; $i < $max_elements; $i++){
foreach($arrays as $array){
if($array[$i]){
$merged[] = $array[$i];
}
}
}