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 关注
- 86 浏览
添加回答
举报