我有两个数组。 数组1是DeptID和dept_number:
之间的映射array(66) {
[0] => array(2) {
'DeptID' → str•4 '1300'
'dept_number' → str•3 '18'
}
[1] => array(2) {
'DeptID' → str•4 '1000'
'dept_number' → str•3 '129'
}
[2] => array(2) {
'DeptID' → str•4 '2400'
'dept_number' → str•3 '101'
}
......等等
数组2具有包含dept_number的商店记录。我想用来自数组1的DeptID值替换dept_number值。
array(27) {
[0] => array(11) {
'org_id' → str•2 '11'
'org_number' → str•2 '11'
'supplier_number' → str•4 '3806'
'supplier_name' → str•17 'TEST1'
'invoice_number' → str•8 'DXXX'
'receive_date' → str•10 '2013-09-11'
'inv_status' → str•7 'Pending'
'final_cost' → str•6 '317.30'
'final_qty' → str•5 '12.00'
'dept_number' → str•2 '18'
'dept_descr' → str•10 'BULK 1'
}
[1] => array(11) {
'org_id' → str•2 '11'
'org_number' → str•2 '11'
'supplier_number' → str•4 '1070'
'supplier_name' → str•24 'TEST2'
'invoice_number' → str•7 'DXXY'
'receive_date' → str•10 '2013-09-11'
'inv_status' → str•7 'Pending'
'final_cost' → str•6 '830.30'
'final_qty' → str•5 '26.00'
'dept_number' → str•2 '101'
'dept_descr' → str•10 'BULK 2'
}
......等等
如何使用阵列1中的DeptID替换阵列2中的dept_number?
答案 0 :(得分:1)
开始制作映射数组的KVP(键值对)数组,其中键是要查找值的任何值(在本例中为dept_number
),并将数组键的值设置为DeptID
:
$deptKVP = array();
foreach ($deptMappings as $deptMapping) {
$deptKVP[$deptMapping['dept_number']] = $deptMapping['DeptID'];
}
/*
$deptKVP = [
18 => 1300,
129 => 1000,
101 => 2400
];
*/
然后简单地遍历常规数组:
foreach ($array2 as &$subArray) {
$subArray['dept_number'] = $deptKVP[$subArray['dept_number']];
}
unset($subArray); //Unset the reference
答案 1 :(得分:0)
如果您的dept_number是唯一的:
foreach ($array1 as $a1)
$array3[ $a1['dept_number'] ] = $a1['DeptId'];
现在你在array3中有一个关联的array1。接下来,迭代array2
foreach($array2 as $key=>$value)
$array2[$key]['DeptId'] = $array3[ $value['dept_number'] ];
答案 2 :(得分:0)
你基本上必须遍历数组2,并针对数组1中的每个dept_number检查每个dept_number值:
foreach($array2 as $arr2_record){
foreach($array1 as $arr1_record){
if($arr2_record['dept_number'] == $arr1_record['dept_number']){
$arr2_record['DeptID'] = $arr1_record['DeptID'];
$arr2_record['dept_number'] = null;
}
}
}
编辑:如果您想维护“dept_number”键,那么您只需将$arr2_record['dept_number']
设置为"DeptID"
的{{1}}