3 回答

TA貢獻1883條經驗 獲得超3個贊
使用array_map您可以解析 csv 數據并根據需要使用數組。例子:
// Parsing the data in csv file
$csv = array_map('str_getcsv', file('path/file.csv'));
/*At this point you already have an array with the data but
* the first row is the header row in your csv file */
//remove header row
array_shift($csv);
$data = [];
//Walk the array and add the needed data into some another array
array_walk($csv, function($row) use (&$data) {
$data[$row[3]] = $row[8];
});
就是這樣。
但是,您作為示例顯示的數據具有重復的 UPC。如果您想要一個具有結構的數組,您將覆蓋一些數據'UPC' => 'Qty'。數組中不能有重復的鍵。
如果您正在尋找的是獲取每個 UPC 的總數量,那么如果 UPC 密鑰已經存在,您只需將現有的數量添加到新的數量。
// Parsing the data in csv file
$csv = array_map('str_getcsv', file('file.csv'));
//remove header row
array_shift($csv);
$data = [];
//Walk the array and add the needed data into another array
array_walk($csv, function($row) use (&$data) {
$data[$row[3]] = ($data[$row[3]] ? $data[$row[3]] + (int) $row[8] : (int) $row[8]);
});
或者更長但更清晰。
//Walk the array and add the needed data into another array
array_walk($csv, function($row) use (&$data) {
if(!empty($data[$row[3]]))
{
$data[$row[3]] += (int) $row[8];
}
else {
$data[$row[3]] = (int) $row[8];
}
});

TA貢獻2051條經驗 獲得超10個贊
下面代碼注釋中的解釋
$array = [];
// Open file "$file" and checking that it is not empty
if (($handle = fopen($file, "r")) !== false) {
// loop on each csv line, stopping at end of file
while (($data = fgetcsv($handle)) !== false) {
// Excluding header row & checking data is not empty
if ($data[0] !== 'Application' && !empty($data[0])) {
// fgetcsv returns an array, on your example UPC is on key 3 and Qty on key 9
$array[] = [$data[3] => $data[9]];
}
}
fclose($handle);
}
return $array;
這里的鍵是硬編碼的,但也許你有辦法動態地放置它,這取決于你的代碼和工作流程。這只是一個簡單的(我希望)演示。

TA貢獻1875條經驗 獲得超3個贊
我使用SplfileObject進行閱讀。然后第一行用作所有值的鍵。帶有列名的array_column現在可以用于所需的結果。
$csv = new SplFileObject('datei.csv');
$csv->setFlags(SplFileObject::READ_CSV?
? | SplFileObject::SKIP_EMPTY?
? | SplFileObject::READ_AHEAD?
? | SplFileObject::DROP_NEW_LINE
);
//Combine first row as key with values
$csvArr = [];
foreach($csv as $key => $row){
? if($key === 0) $firstRow = $row;
? else $csvArr[] = array_combine($firstRow,$row);
}
$arrQty = array_column($csvArr,'Qty','UPC');
- 3 回答
- 0 關注
- 152 瀏覽
添加回答
舉報