Given two arrays, I want to join them together in such a way that chosen elements can be transfered from one to the other, and came up with a way to do this as shown.
$a1 = array(
0 => array('this'=>1,'that'=>'x'),
1 => array('this'=>2,'that'=>'y'),
2 => array('this'=>3,'that'=>'z'),
);
$b1 = array(
0 => array('this'=>1,'other'=>'a'),
1 => array('this'=>2,'other'=>'b'),
2 => array('this'=>3,'other'=>'c'),
3 => array('this'=>4,'other'=>'d'),
4 => array('this'=>5,'other'=>'e'),
);
function meldArrays( $to_add, $to_return, $join_on, $transfer ){
foreach($to_add as $v){
foreach( $to_return as $k2=>$v2 ){
if( $v2[$join_on] === $v[$join_on] ){
if( array_key_exists($transfer, $v) ){
$to_return[$k2][$transfer] = $v[$transfer];
}
}
}
}
return $to_return;
}
So when called with a) the arrays the right way round b) the key and value to join on and c) which key I want adding to the target array - like so:
$result = meldArrays($a1, $b1, 'this','that') ;
var_dump( $result );
It works and I get results I would expect:
array
0 =>
array
'this' => int 1
'other' => string 'a' (length=1)
'that' => string 'x' (length=1)
1 =>
array
'this' => int 2
'other' => string 'b' (length=1)
'that' => string 'y' (length=1)
2 =>
array
'this' => int 3
'other' => string 'c' (length=1)
'that' => string 'z' (length=1)
3 =>
array
'this' => int 4
'other' => string 'd' (length=1)
4 =>
array
'this' => int 5
'other' => string 'e' (length=1)
My question is, isn’t there really a simpler way of doing this? I feel I have missed something obvious here…
You can swop the arrays round, leave the join as is, and choose ‘other’:
$result = meldArrays($b1, $a1, 'this','other') ;
var_dump( $result );
and it works too:
array
0 =>
array
'this' => int 1
'that' => string 'x' (length=1)
'other' => string 'a' (length=1)
1 =>
array
'this' => int 2
'that' => string 'y' (length=1)
'other' => string 'b' (length=1)
2 =>
array
'this' => int 3
'that' => string 'z' (length=1)
'other' => string 'c' (length=1)
Comments?