前端表單包含多組同名輸入框 (如動態新增行),提交後需判斷多組記錄的 part、transysno、tranlineid 是否完全相同,相同則合併 count 求和。
<form action="process.php" method="post">
<!-- 第 1 組 -->
<input name="part[]" type="text" />
<input name="transysno[]" type="text" />
<input name="tranlineid[]" type="text" />
<input name="count[]" type="number" />
<!-- 第 2 組 (JS 動態新增) -->
<input name="part[]" type="text" />
<input name="transysno[]" type="text" />
<input name="tranlineid[]" type="text" />
<input name="count[]" type="number" />
<button type="submit">提交</button>
</form>
name="part[] 讓 PHP 自動將同名欄位解析為陣列 $_POST['part'] = [val1, val2, ...]。
<?php
function processFormRows(array $post): array
{
$part = $post['part'] ?? [];
$transysno = $post['transysno'] ?? [];
$tranlineid = $post['tranlineid'] ?? [];
$count = $post['count'] ?? [];
$rowCount = count($part);
if ($rowCount === 0) return [];
// 1. 組裝原始行資料
$rows = [];
for ($i = 0; $i < $rowCount; $i++) {
$rows[] = [
'part' => trim((string)($part[$i] ?? '')),
'transysno' => trim((string)($transysno[$i] ?? '')),
'tranlineid' => trim((string)($tranlineid[$i] ?? '')),
'count' => (float)($count[$i] ?? 0),
];
}
// 2. 以三欄組合為鍵分組求和
$groups = [];
foreach ($rows as $row) {
$key = $row['part'] . '|' . $row['transysno'] . '|' . $row['tranlineid'];
if (!isset($groups[$key])) {
$groups[$key] = $row;
} else {
$groups[$key]['count'] += $row['count'];
}
}
// 3. 返回合併後列表 (可選保留原順序)
return array_values($groups);
}
// 使用
$merged = processFormRows($_POST);
// 輸出結果
foreach ($merged as $row) {
echo "{$row['part']} | {$row['transysno']} | {$row['tranlineid']} | Count: {$row['count']}
";
}
<?php
function mergeDuplicateRows(array $rows, array $keyFields, string $sumField): array
{
$groups = [];
foreach ($rows as $row) {
$keyParts = [];
foreach ($keyFields as $field) {
$keyParts[] = $row[$field] ?? '';
}
$key = implode('|', $keyParts);
if (!isset($groups[$key])) {
$groups[$key] = $row;
} else {
$groups[$key][$sumField] = ($groups[$key][$sumField] ?? 0) + ($row[$sumField] ?? 0);
}
}
return array_values($groups);
}
// 使用
$rows = [
['part'=>'A','sys'=>'S1','line'=>'L1','count'=>10],
['part'=>'B','sys'=>'S2','line'=>'L2','count'=>5],
['part'=>'A','sys'=>'S1','line'=>'L1','count'=>3], // 重複
];
$merged = mergeDuplicateRows($rows, ['part','sys','line'], 'count');
// 結果: A|S1|L1 count=13, B|S2|L2 count=5
若數據最終入庫,可直接用 SQL ON DUPLICATE KEY UPDATE:
<?php
// 假設表有唯一索引 UNIQUE KEY uk_part_sys_line (part, transysno, tranlineid)
$sql = "INSERT INTO `trans_detail` (part, transysno, tranlineid, count) VALUES ";
$params = [];
$placeholders = [];
foreach ($rows as $row) {
$placeholders .= '(?,?,?,?),';
$params[] = $row['part'];
$params[] = $row['transysno'];
$params[] = $row['tranlineid'];
$params[] = $row['count'];
}
$sql = rtrim($sql, ',') . ' ON DUPLICATE KEY UPDATE `count` = `count` + VALUES(`count`)';
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
單次 SQL 完成去重累加,效能遠超 PHP 端處理。
<script>
document.querySelector('form').addEventListener('submit', e => {
const parts = [...document.querySelectorAll('[name="part[]"]')].map(i => i.value.trim());
const sys = [...document.querySelectorAll('[name="transysno[]"]')].map(i => i.value.trim());
const line = [...document.querySelectorAll('[name="tranlineid[]"]')].map(i => i.value.trim());
const seen = new Set();
for (let i = 0; i < parts.length; i++) {
const key = parts[i] + '|' + sys[i] + '|' + line[i];
if (seen.has(key)) {
alert(`第 ${i+1} 行與前面資料重複,將自動合併數量`);
// 可選:攔截提交讓用戶確認
}
seen.add(key);
}
});
</script>
核心模式:前端陣列命名 → 後端組裝鍵分組聚合 → 或直接資料庫 UPSERT,簡潔高效解決動態表單重複行合併需求。