Wednesday, 29 August 2018

To merge two multidimensional arrays based on the combination of elements of an array in PHP

I have two arrays. I want to add $inv_new to $inv_h where StoreNumber = org_number, SupplierNumber = supplier_number and InvoiceNumber = invoice_number I have tried array_merge, but I can't determine how to match the keys in the two arrays so that the new elements are added where the "keys" match.

vdump($inv_new);
 array(1) {
   [0] => array(6) {
   'StoreNumber' → str•3 '11 '
   'SupplierNumber' → str•4 '6303'
   'InvoiceNumber' → str•11 'DI613718812'
   'ReasonCode' → str•4 'Dept'
   ["ReasonNote"] → NULL
   ["ResolutionCode"] → NULL
   }
 }
 vdump($inv_h);
 array(30) {
  ....
   [22] => array(5) {
   'org_id' → str•2 '11'
   'org_number' → str•2 '11'
   'supplier_number' → str•4 '6303'
   'supplier_name' → str•27 'BLAH'
   'invoice_number' → str•11 'DI613718812'
   }

would result in:
      array(30) {
  ....
   [22] => array(8) {
   'org_id' → str•2 '11'
   'org_number' → str•2 '11'
   'supplier_number' → str•4 '6303'
   'supplier_name' → str•27 'BLAH'
   'invoice_number' → str•11 'DI613718812'
   'ReasonCode' -> str 4 'Dept'
   ["ReasonNote"] -> NULL
   ["ResolutionCode"] -> NULL
   }


Just use loops to match the corresponding elements and then use array_merge() on the elements to copy the fields.
foreach ($inv_new as $inv1) {
    foreach ($inv_h as &$inv2) {
        if ($inv1['StoreNumber'] == $inv2['org_id']
            && $inv1['SupplierNumber'] == $inv2['supplier_number']
            && $inv1['InvoiceNumber'] == $inv2['invoice_number']) {
            $inv2 = array_merge($inv1, $inv2);
            break;
        }
    }
}

0 comments:

Post a Comment