1 回答

TA貢獻1828條經驗 獲得超4個贊
您當前的代碼適用于兩種情況:
按原樣讀取所有數據,不加修改
讀取所有數據并執行通用修改
由于您需要的是條件修改,因此您最好手動創建數組的結構。這樣做會增加另一個好處:代碼清晰度。您應該始終爭取描述性代碼,因此使用描述性關聯鍵構建數組將使代碼的意圖更加清晰。
基于示例數據的建議解決方案(您應該根據您的特定需求定制的粗略草圖):
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;
}
現在,您訂單中的所有項目都整齊地存儲為子數組,每個子數組僅包含該項目的特定數據,這使得迭代變得非常容易:
foreach($orders[$orderId]['items'] as $item)
- 1 回答
- 0 關注
- 115 瀏覽
添加回答
舉報