首页 > 解决方案 > 对来自多个数组的唯一数据求和

问题描述

我有两个来自不同数据库的数组,现在我必须将它作为组合报告打印在表格中。这些数组是

array:3 [▼
  0 => array:6 [▼
    "count_id" => 5
    "count_name" => "NE 28/1"
    "order_qty" => 75100
    "balance_qty" => 75100
    "stock_qty" => "0"
    "order_req" => 75100
  ]
  1 => array:6 [▼
    "count_id" => 13
    "count_name" => "NE 20/1 KH"
    "order_qty" => 2200
    "balance_qty" => 2200
    "stock_qty" => "48400"
    "order_req" => 0.0
  ]
]

和第二个数组

array:2 [▼
  0 => array:6 [▼
    "count_id" => 13
    "count_name" => "NE 20/1 KH"
    "order_qty" => 2200
    "balance_qty" => 2200
    "stock_qty" => "45420.85"
    "order_req" => 0.0
 ]
 1 => array:6 [▼
   "count_id" => 24
   "count_name" => "NE 24/1 KH"
   "order_qty" => 5150
   "balance_qty" => 5150
   "stock_qty" => "45420.85"
   "order_req" => 0.0
 ]
]

现在我需要常见的“count_name”,如“NE 20/1 KH”值将只求和并打印一次。就像是...

array:3 [▼
  0 => array:6 [▼
    "count_id" => 5
    "count_name" => "NE 28/1"
    "order_qty" => 75100
    "balance_qty" => 75100
    "stock_qty" => "0"
    "order_req" => 75100
  ]
  1 => array:6 [▼
    "count_id" => 13
    "count_name" => "NE 20/1 KH"
    "order_qty" => 4400
    "balance_qty" => 4400
    "stock_qty" => "96800"
    "order_req" => 0.0
  ]
  2 => array:6 [▼
    "count_id" => 24
    "count_name" => "NE 24/1 KH"
    "order_qty" => 5150
    "balance_qty" => 5150
    "stock_qty" => "45420.85"
    "order_req" => 0.0
  ]
]

我尝试通过两个 foreach 循环来做到这一点,但它没有用。它会多次打印每个数据。那么有没有人可以帮助我,拜托。

标签: phplaravel

解决方案


它可以完成,但首先通过数据库查询将它们组合起来可能更容易。

// Your arrays of data
$data = [$array1, $array2];

// The fields you want to sum
$sumFields = ['order_qty', 'balance_qty', 'stock_qty', 'order_req'];

// The final array
$combined = [];

foreach ($data as $arr) {
    foreach ($arr as $item) {
        $key = $item['count_id'];
        if (!isset($combined[$key])) {
            $combined[$key] = $item;
        } else {
            foreach ($sumFields as $field) {
                $combined[$key][$field] += $item[$field];
            }
        }
    }
}

// Print result
print_r($combined);

推荐阅读