1 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
您當(dāng)前的代碼適用于兩種情況:
按原樣讀取所有數(shù)據(jù),不加修改
讀取所有數(shù)據(jù)并執(zhí)行通用修改
由于您需要的是條件修改,因此您最好手動(dòng)創(chuàng)建數(shù)組的結(jié)構(gòu)。這樣做會(huì)增加另一個(gè)好處:代碼清晰度。您應(yīng)該始終爭(zhēng)取描述性代碼,因此使用描述性關(guān)聯(lián)鍵構(gòu)建數(shù)組將使代碼的意圖更加清晰。
基于示例數(shù)據(jù)的建議解決方案(您應(yīng)該根據(jù)您的特定需求定制的粗略草圖):
function readCSV($csvFile)
{
$output = [];
$fileHandle = fopen($csvFile, 'r');
$header = fgetcsv($fileHandle);
while (!feof($fileHandle)) {
$fileRow = fgetcsv($fileHandle, 1024);
$orderId = $fileRow[0];
// skip this row if it's empty (the first field contains no id)
if (empty($orderId)) {
continue;
}
/*
$fileRow[3] is "Buyer name", the first field that's present in one type of row
(the one containing common properties of the order). By checking if it's empty,
we identify the contents of the row - not empty means order row with common
properties, empty means item row with specific item properties.
*/
if (!empty($fileRow[3])) {
// no need to repeat the id inside the array - it's already stored in the key
$output[$orderId] = [
'order_number' => $fileRow[1],
'buyer_username' => $fileRow[2],
'buyer_name' => $fileRow[3],
// here you can continue explicitly adding any property you need
];
} else {
// add a new item entry
$output[$orderId]['items'][] = [
'item_number' => $fileRow[20],
'item_title' => $fileRow[21],
'quantity' => $fileRow[24],
'price' => $fileRow[25],
// here you can continue explicitly adding any property you need
];
}
}
fclose($fileHandle);
return $output;
}
現(xiàn)在,您訂單中的所有項(xiàng)目都整齊地存儲(chǔ)為子數(shù)組,每個(gè)子數(shù)組僅包含該項(xiàng)目的特定數(shù)據(jù),這使得迭代變得非常容易:
foreach($orders[$orderId]['items'] as $item)
- 1 回答
- 0 關(guān)注
- 107 瀏覽
添加回答
舉報(bào)