I have an array
array (
array (
'id_product' => '10',
'id_supplier' => '0'
),
array (
'id_product' => '11',
'id_supplier' => '0'
)
)
and a second one I want to merge with first one
array (
array (
'id_product' => '10',
'date' => '12/02/2014'
)
)
I need to get
array (
array (
'id_product' => '10',
'id_supplier' => '0',
'date' => '12/02/2014'
),
array (
'id_product' => '11',
'id_supplier' => '0'
)
)
I know I could use a foreach in one and look for an existing value in the second one but what's the most efficient way? Is there a php function for that kind of mixing? I looked to array_merge() but doesn't seems what I need
Following deceze comment, I ended up using:
foreach ($array1 as $key => $value1) {
foreach ($array2 as $key2 => $value2)
if ($value1['id_product'] == $value2['id_product'])
{
$array1[$key] = array_merge($array1[$key], $array2[$key2]);
}
}
this function gave me same result, thanks to TBI, but only if I needed to merge arrays based on their position within $a and $b, witch isn't the case
$result = array_replace_recursive(array1, array2)
Here is the complete working code:-
$a = array (
array (
'id_product' => '10',
'id_supplier' => '0'
),
array (
'id_product' => '11',
'id_supplier' => '0'
)
);
$b = array (
array (
'id_product' => '10',
'date' => '12/02/2014'
)
);
function my_array_merge(&$array1, &$array2) {
$result = Array();
foreach($array1 as $key => &$value) {
$a++;
echo $a;
if(!empty($array2[$key]) && !empty($array2[$key])){
$result[$key] = array_merge($value, $array2[$key]);
}
if(empty($array2[$key])){
$result[$key] = $value;
}
}
return $result;
}
$array = my_array_merge($a, $b);
echo "<pre>";
print_r($array);
Try this -
$a = array (
array (
'id_product' => '10',
'id_supplier' => '0'
),
array (
'id_product' => '11',
'id_supplier' => '0'
));
$b = array (
array (
'id_product' => '10',
'date' => '12/02/2014'
));
I have used array_merge_recursive function to get the combined array :-
$c = array_replace_recursive($a, $b);
$c is the result that you wanted to show.