phparraysmultidimensional-arraymerging-data

Update row data in a 2d array if its identifying column is found in another array


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 = [
    ['name' => "pano", 'code' => "BR0001", 'qty' => "2", 'price' => "12"],
    ['name' => "ying", 'code' => "AB001", 'qty' => "5", 'price' => "8"]
];

And I want to merge the second array:

$new_product = [
    '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 = [
    ['name' => "pano", 'code' => "BR0001", 'qty' => "10", 'price' => "12"],
    ['name' => "ying", 'code' => "AB001", 'qty' => "5", 'price' => "8"]
];

Solution

  • 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>';