Reputation: 2949
I have 3 arrays:
array(1, 5, 1);
array(3, 2, 7, 5 ,4);
array(4, 3, 6, 5)
I want to merge them and get such result:
array(
array(1, 3, 4),
array(5, 2, 3),
array(1, 7, 6),
array(5, 5),
array(4)
);
What is the easiest way?
Upvotes: 1
Views: 96
Reputation: 1794
Is this what you want?
You can use array_map
<?php
$a = array( 1, 5, 1 );
$b = array( 3, 2, 7, 5 ,4 );
$c = array( 4, 3, 6, 5 );
$d = array_map( function() {
return array_filter( func_get_args() );
}, $a, $b, $c );
print_r( $d );
?>
Output
Array
(
[0] => Array
(
[0] => 1
[1] => 3
[2] => 4
)
[1] => Array
(
[0] => 5
[1] => 2
[2] => 3
)
[2] => Array
(
[0] => 1
[1] => 7
[2] => 6
)
[3] => Array
(
[1] => 5
[2] => 5
)
[4] => Array
(
[1] => 4
)
)
Upvotes: 1
Reputation: 324650
Assuming you have the latest version of PHP (5.5), you can use this:
$input = array(
array(1,5,1),
array(3,2,7,5,4),
array(4,3,6,5)
);
$output = array_column($input,null);
If you don't have the latest version, see the original PHP version for a shim.
Alternatively, for this specific case (ie. a specialised shim), try this:
$input = array(...); // see code block above
$output = array();
foreach($input as $arr) foreach($arr as $i=>$v) $output[$i][] = $v;
Upvotes: 3
Reputation: 141827
$arrs = array(
array(1, 5, 1),
array(3, 2, 7, 5, 4),
array(4, 3, 6, 5),
);
$result = array();
$num_arrs = count($arrs);
for($i = 0; $i < $num_arrs; $i++){
$size = count($arrs[$i]);
for($j = 0; $j < $size; $j++){
if(!isset($result[$j]))
$result[$j] = array();
$result[$j][] = $arrs[$i][$j];
}
}
Upvotes: 5
Reputation: 1015
$arrays = array(
array(1, 5, 1),
array(3, 2, 7, 5 ,4),
array(4, 3, 6, 5)
);
$combined = array();
foreach($arrays as $array) {
foreach($array as $index => $val) {
if(!isset($combined[$index])) $combined[$index] = array();
$combined[$index][] = $val;
} }
After that $combined
holds what you want.
Upvotes: 1