我有两个数组。我想将$ inv_new添加到$ inv_h,其中StoreNumber = org_number,SupplierNumber = supplier_number和InvoiceNumber = invoice_number 我试过了array_merge,但我无法确定如何匹配两个数组中的键,以便在“键”匹配的地方添加新元素。
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'
}
会导致:
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
}
答案 0 :(得分:1)
在这种情况下,最好只手动分配值,因为键有不同的命名约定,array_unique可能会阻止分配多个空值。
//iterate over the main array
foreach ($inv_h as $hkey => $hval) {
//build our if statement (nice and tidy)
$store_match = ($hval['org_number'] == $inv_new[0]['StoreNumber']);
$supplier_match = ($hval['supplier_number'] == $inv_new[0]['SupplierNumber']);
$invoice_match = ($hval['invoice'] == $inv_new[0]['InvoiceNumber']);
if ($store_match && $supplier_match && $invoice_match) {
//assign array values manually
//cant use array merge because we would end up with some duplicates
//due to different naming conventions (org_number vs StoreNumber)
$inv_h[$hkey]['ReasonCode'] = $inv_new[0]['ReasonCode'];
$inv_h[$hkey]['ReasonNote'] = $inv_new[0]['ReasonNote'];
$inv_h[$hkey]['ResolutionCode'] = $inv_new[0]['ResolutionCode'];
}
}
答案 1 :(得分:0)
只需使用循环来匹配相应的元素,然后在元素上使用array_merge()
来复制字段。
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;
}
}
}