Reputation: 5
Hi I am new in PHP and I am trying to merge 2 arrays but I don't want to get duplicates.I have been stuck a week now. I have first array:
$existed_product = array(array('name'=>"pano", 'code'=>"BR0001", 'qty'=>"2", 'price'=>"12"),
array('name'=>"ying", 'code'=>"AB001", 'qty'=>"5", 'price'=>"8"));
And I want to merge the second array:
$new_product= array('name'=>"pano", 'code'=>"BR0001", 'qty'=>"10", 'price'=>"12");
I want to merge them and when it found duplicate product, just replace it with a newer array(has qty=10). The result looks like this:
$final_array=array(array('name'=>"pano", 'code'=>"BR0001", 'qty'=>"10", 'price'=>"12"),
array('name'=>"ying", 'code'=>"AB001", 'qty'=>"5", 'price'=>"8"));
Please help me.Thank you
Upvotes: 0
Views: 29
Reputation: 691
Assuming new product always is a single array, and code is the identifyer, something like this
$existed_product = array(
array(
'name' => 'pano',
'code' => 'BR0001',
'qty' => '2',
'price' => '12' ),
array(
'name' => 'ying',
'code' => 'AB001',
'qty' => '5',
'price' => '8'
)
);
echo '<pre>', print_r( $existed_product, true ), '</pre>';
$new_product = array(
'name' => 'pano',
'code' => 'BR0001',
'qty' => '10',
'price' => '12'
);
foreach ( $existed_product as $no => $product ) {
if ( $new_product['code'] == $product['code'] ) {
$existed_product[$no]['qty'] = $new_product['qty'];
$existed_product[$no]['price'] = $new_product['price'];
}
}
echo '<pre>', print_r( $existed_product, true ), '</pre>';
Upvotes: 1