【发布时间】:2017-09-22 10:50:42
【问题描述】:
我有一个使用 PHP 读取的 CSV 文件。它是一个逗号分隔的 CSV 文件,它将每行数据拆分为一个数组。本例中的数组是$fields。完成所有处理后,数组将作为 XML 文件输出。
$fields[ 0 ] 包含每一行的参考编号。某些行可能具有相同的参考编号,表示项目在一起,因此$total_gross_weight 将是当前参考的值 + 下一个参考。
我有一个 for 循环遍历数组并处理它们。
For循环
//set variable to empty
$previous_consignee_id = "";
$total_gross_weight = 0;
$total_volume = 0;
$total_net_weight = 0;
//for loop to loop over arrays
for( $counter = 0; $counter < count( $buffer ); $counter++ ) {
//$fields is the array, split with a comma
$fields = split( ",", $buffer[ $counter ] );
//set consignee_id as the first field in each array
//example of consignee_id = DUN72049214
$consignee_id = trim( $fields[ 0 ] );
//if the consignee_id is not equal to $previous_consignee_id
//and $previous_consignee_id is not empty
if( $consignee_id != $previous_consignee_id ) {
//set $total_gross_weight to fields[ 60 ]
//$fields[ 60 ] is always the weight
$total_gross_weight = $fields[ 60 ];
//run create_job method
//this method works fine so no changes needed to it
create_job( $xml, $fields, $total_gross_weight );
echo "creating new job ".$consignee_id." weight is ".$total_gross_weight."\n";
} else {
//if the $consignee_id matches the previous_consignee_id
//total_gross_weight is the current $total_gross_weight + $fields[ 60 ]
$total_gross_weight = $total_gross_weight + $fields[ 60 ];
echo "same job ".$consignee_id." weight is ".$total_gross_weight."\n";
}
//set $previous_consignee_id to the current $consignee_id;
$previous_consignee_id = $consignee_id;
}//endfor
For循环的结果
creating new job DN1234567 weight is 500
creating new job DN1234568 weight is 500
same job DN1234568 weight is 1000
creating new job DN1234569 weight is 500
creating new job DN1234570 weight is 500
creating new job DN1234571 weight is 500
creating new job DN1234572 weight is 500
same job DN1234572 weight is 1000
same job DN1234572 weight is 1500
creating new job DN1234573 weight is 500
creating new job DN1234574 weight is 500
creating new job DN1234575 weight is 500
same job DN1234575 weight is 1000
creating new job DN1234576 weight is 500
creating new job DN1234577 weight is 500
same job DN1234577 weight is 1000
creating new job DN1234578 weight is 500
creating new job DN1234579 weight is 500
creating new job DN1234580 weight is 500
问题在于,第一份工作 (DN1234567) 与“相同的工作”相呼应。但是,既然是第一份工作,就应该作为“新工作”来呼应。如您所见,当工作参考与前一个相同时,将权重相加以将其合并为一个。但是,之后的以下工作具有不正确的值,因为它似乎带有“相同的工作”值。
我尝试在每次迭代后取消设置变量,但我似乎无法弄清楚。我认为 If 语句的条件存在问题,因为在第一次迭代中“previous_consignee_id”为空,导致它跳到 else 语句。
谁能给我一些关于如何解决这个问题的指示。
【问题讨论】: