0

我有两个数组。数组 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'
}

...等等

如何将 Array 2 中的 dept_number 替换为 Array 1 中的 DeptID?

4

3 回答 3

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
于 2013-09-16T19:44:51.873 回答
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'] ];
于 2013-09-16T19:44:45.190 回答
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"$arr1_record

于 2013-09-16T19:47:26.563 回答