[英]Merge two associative arrays in PHP
I have two arrays in PHP that I want to merge. 我有两个要合并的PHP数组。 An example of the first array, which is a list of Department and Classes, along with Class totals:
第一个数组的示例是Department和Classes以及Class总计的列表:
vdump($cl_subtotal);
array(2) {
'None' → array(1) {
'None' → float 132.88
}
'instore bakery' → array(10) {
'pies' → float 70.94
'cakes' → float 146.71
'miscellaneous' → float 25.57
'cookies' → float 52.38
'brownies' → float 33.96
'rolls' → float 143.02
'danish' → float 90.42
'bagels & pretzels' → float 85.68
'breads' → float 55.73
'dessert case' → float 81.83
}
}
The second array is the Class detail records, and I want them to appear under each Class in the first array. 第二个数组是“类”详细信息记录,我希望它们出现在第一个数组的每个“类”下。 There's a catch.
有一个陷阱。 In this second array, if there is no Department or Class, the array key is blank ('').
在第二个数组中,如果没有Department或Class,则数组键为空白('')。 The Department/Class will always both be blank, or they will both contain a string (so there will never be a case where Department is blank, but Class is not blank).
Department / Class始终都为空白,或者都包含一个字符串(因此,永远不会出现Department为空,但Class不为空)。 These records with blank Department/Class in the second array should be associated with the record in the first array where Department = "None" and Class = "None".
这些第二个数组中部门/类别为空的记录应与第一个数组中的部门=“ None”和Class =“ None”的记录相关联。
This is an example of the second array: 这是第二个数组的示例:
vdump($groups);
array(2) {
'instore bakery' → array(10) {
'pies' → array(2) {
[0] => array(12) {
'UPC' → str•13 '0004712503209'
'Department_Desc' → str•14 'instore bakery'
'Class_Desc' → str•4 'pies'
'store' → str•2 '11'
'supplier_number' → str•4 '6303'
'invoice_number' → str•11 'DI613728199'
'seq' → str•1 '1'
'item_id' → str•14 '00047125032097'
'item_description' → str•9 'MARIONBRY'
'dept_number' → str•2 '17'
'final_qty' → str•4 '5.00'
'final_cost' → str•5 '37.65'
}
and here's an example record with blank Department/Class: 这是带有空白部门/类别的示例记录:
[""] => array(1) {
[""] => array(4) {
[0] => array(10) {
'store' → str•2 '11'
'supplier_number' → str•4 '6303'
'invoice_number' → str•11 'DI613728199'
'seq' → str•1 '8'
'item_id' → str•14 '00047125032332'
'UPC' → str•13 '0004712503233'
'item_description' → str•9 'NOT FOUND'
'dept_number' → str•1 '0'
'final_qty' → str•4 '2.00'
'final_cost' → str•5 '20.96'
}
Here's how I resolved this: I first replaced the empty keys in the second array ($groups). 解决方法如下:我首先替换了第二个数组($ groups)中的空键。 I then did:
然后我做了:
foreach($cl_subtotal as $grname => &$itemlist ){
foreach($itemlist as $ilk => &$ilv){
$ilv = array(
'value' => $ilv,
);
foreach($groups[$grname][$ilk] as $k => $v) {
$ilv[$k] = $v;
}
}
}
to merge the array with details into the summary array. 将具有详细信息的数组合并到摘要数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.