Reputation: 938
So I have 2 arrays like so:
$a = array(array('1','2','3'), array('hello','darkness','my'));
$b = array(array('4','5','6'), array('old','friend','I'));
Now I want to merge the subarrays respectively:
$result = array(array_merge($a[0],$b[0]),array_merge($a[1],$b[1])));
Resulting in:
#vardump($result)
array(2) {
[0]=>
array(6) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
[3]=>
string(1) "4"
[4]=>
string(1) "5"
[5]=>
string(1) "6"
}
[1]=>
array(6) {
[0]=>
string(5) "hello"
[1]=>
string(8) "darkness"
[2]=>
string(2) "my"
[3]=>
string(3) "old"
[4]=>
string(6) "friend"
[5]=>
string(1) "I"
}
}
Well this works... but it just looks clumsy and it isn't a good solution if there would be a variable amount of subarrays I need to merge. Is there a build-in function for this kind of operation (or a more "acceptable" way to do this)?
Upvotes: 0
Views: 36
Reputation: 938
I came up with the following (with the help of @panther's answer)
function subarray_merge(...$arrays){
$result = array();
foreach ($arrays as $k => $v) {
if($k === 0) {
$result = $v;
}else{
foreach ($v as $ks => $vs) {
$result[$ks] = array_merge($result[$ks], $v[$ks]);
}
}
}
return $result;
}
print_r(subarray_merge($a,$b,$c));
Upvotes: 1
Reputation: 27092
Just use a foreach
cycle.
<?php
$a = array(array('1','2','3'), array('hello','darkness','my'));
$b = array(array('4','5','6'), array('old','friend','I'));
$c = array(array('7','8','9'), array('old','friend','I'));
$defined_vars = get_defined_vars();
$result = [];
foreach ($defined_vars as $key => $arr) {
if (in_array($key, ['_GET', '_POST', '_COOKIE', '_FILES', '_SESSION'])) continue;
foreach ($arr as $k => $row) {
if (!isset($result[$k])) {
$result[$k] = $row;
} else {
foreach ($row as $r) {
$result[$k][] = $r;
}
}
}
}
echo '<pre>';
print_r($result);
--- result
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
)
[1] => Array
(
[0] => hello
[1] => darkness
[2] => my
[3] => old
[4] => friend
[5] => I
[6] => old
[7] => friend
[8] => I
)
)
This solution is 'hell', but working. Correct is to make wrapping array instead these variables, like
$array = [
array(array('1','2','3'), array('hello','darkness','my')),
array(array('4','5','6'), array('old','friend','I')),
array(array('7','8','9'), array('old','friend','I'))
];
$result = [];
foreach ($array as $key => $arr) {
foreach ($arr as $k => $row) {
if (!isset($result[$k])) {
$result[$k] = $row;
} else {
foreach ($row as $r) {
$result[$k][] = $r;
}
}
}
}
echo '<pre>';
print_r($result);
Upvotes: 0