I have two multidimensional arrays, example:
array(
'a' => array(
'code1' => array('v1', 'v2'),
'code2' => array('v1', 'v2')
),
'b' => array(
'code3' => array('v1', 'v2'),
'code4' => array('v1', 'v2'),
'code5' => array('v1', 'v2'),
'code6' => array('v1', 'v2')
)
)
and
array(
'a' => array(
'code1' => '',
),
'b' => array(
'code5' => ''
)
)
My desired result is:
array(
'a' => array(
'code1' => array('v1', 'v2')
),
'b' => array(
'code5' => array('v1', 'v2')
)
)
I'm pretty sure it could be possible using one of built-in php functions, however I'm stuck with it, and can't find a solution rather than manually iterating through array. Can you help me with that?
The exact solution would depend on what you want to happen if the two arrays don't exactly match key-wise, but one way to reach your desired result is:
$a = array(
'a' => array(
'code1' => array('v1', 'v2'),
'code2' => array('v1', 'v2')
),
'b' => array(
'code3' => array('v1', 'v2'),
'code4' => array('v1', 'v2'),
'code5' => array('v1', 'v2'),
'code6' => array('v1', 'v2')
)
);
$b = array(
'a' => array(
'code1' => '',
),
'b' => array(
'code5' => ''
)
);
$result = array();
foreach ($a as $key => $data) {
$result[$key] = array_intersect_key($data, $b[$key]);
}
The idea is to use array_intersect_key
to keep only those elements from $a
that appear (as keys) in $b
.