You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP将CSV转为以UPC为键、Qty为值的关联数组?

Convert CSV to PHP Associative Array (UPC as Key, Qty as Value)

Hey there! Let's get this CSV conversion sorted out for you. The goal is to turn your inventory CSV into a PHP associative array where each key is a UPC value, and the corresponding value is the Qty from that row. I'll walk you through a robust solution, plus address that tricky duplicate UPC scenario from your example.

Step-by-Step PHP Implementation

This approach uses PHP's built-in fgetcsv function, which is efficient even for large CSV files (it reads rows one at a time instead of loading the whole file into memory). It also uses the CSV headers to map columns, so it won't break if your column order changes later.

<?php
// Replace with your actual CSV file path
$csvFilePath = 'inventory.csv';
$upcQtyArray = [];

// Open the CSV file for reading
if (($fileHandle = fopen($csvFilePath, 'r')) !== false) {
    // First, read the header row to get column names
    $headers = fgetcsv($fileHandle);
    
    // Find the index positions of UPC and Qty columns
    $upcColumnIndex = array_search('UPC', $headers);
    $qtyColumnIndex = array_search('Qty', $headers);
    
    // Loop through each data row
    while (($rowData = fgetcsv($fileHandle)) !== false) {
        // Make sure we have valid UPC and Qty values
        if (isset($rowData[$upcColumnIndex], $rowData[$qtyColumnIndex]) && !empty($rowData[$upcColumnIndex])) {
            $upc = $rowData[$upcColumnIndex];
            $qty = $rowData[$qtyColumnIndex];
            
            // Note: In PHP, duplicate array keys will overwrite the previous value
            // For your example, 673131100064 will end up with a value of '6' (not '29')
            $upcQtyArray[$upc] = $qty;
        }
    }
    
    // Close the file handle
    fclose($fileHandle);
}

// Output the resulting array
print_r($upcQtyArray);
?>

Handling Duplicate UPCs

Your sample CSV has duplicate UPC values (like 673131100064 appearing twice with different Qty values). PHP doesn't allow duplicate keys in associative arrays—later values will always overwrite earlier ones. If you need to handle this, here are two common options:

Option 1: Sum Qty for Duplicate UPCs

If you want to calculate the total quantity for each UPC, modify the row processing part like this:

if (isset($rowData[$upcColumnIndex], $rowData[$qtyColumnIndex]) && !empty($rowData[$upcColumnIndex])) {
    $upc = $rowData[$upcColumnIndex];
    $qty = (int)$rowData[$qtyColumnIndex]; // Cast to integer for arithmetic
    
    if (isset($upcQtyArray[$upc])) {
        $upcQtyArray[$upc] += $qty; // Add to existing quantity
    } else {
        $upcQtyArray[$upc] = $qty; // Initialize new UPC entry
    }
}

Option 2: Store All Qty Values for a UPC

If you need to keep track of every individual Qty entry for a UPC, store them as an array:

if (isset($rowData[$upcColumnIndex], $rowData[$qtyColumnIndex]) && !empty($rowData[$upcColumnIndex])) {
    $upc = $rowData[$upcColumnIndex];
    $qty = $rowData[$qtyColumnIndex];
    
    $upcQtyArray[$upc][] = $qty; // Append Qty to the UPC's array
}

This will give you an array like:

array(
    '673131100064' => array('29', '6'),
    '673131100316' => array('26')
);

内容的提问来源于stack exchange,提问作者Abhik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:12:49