这些是我的数据库:
database.csv:
barcode, Name , Qty ,Code
123456 ,Rothmans Blue , 40 ,RB44
234567 ,Rothmans Red , 40 ,RB30
345678 ,Rothmans Green , 40 ,RB20
456789 ,Rothmans Purple, 40 ,RB10
567890 ,Rothmans Orange, 40 ,RB55
stocktakemain.csv:
barcode, Name , Qty ,Code,ScQty
123456 ,Rothmans Blue , 40 ,RB44, 1
234567 ,Rothmans Red , 40 ,RB30, 1
过程:
- 网站有一个输入扫描,张贴到"条形码"。
- 它将检查'database.csv'中是否存在条形码
- 如果条形码存在并且不在' stocktakkeep .csv'中,它将以ScQty为1将其添加到' stocktakkeep .csv'中。请参阅下面代码中的第2节。
- ELSE当扫描stocktakemain.csv中的现有条形码时,将'stocktakemain.csv'与+1(加1)附加到该特定行的ScQty。
代码:
function searchForBarcode($id, $array)
{
foreach ($array as $key => $val)
{
if (in_array($id, $val))
{
return $key;
}
}
return null;
}
$post = $_POST["barcode"];
$dbcsv = fopen('databases/database.csv', 'r');
$csvArray = array();
while(! feof($dbcsv))
{
$csvArray[] = fgetcsv($dbcsv);
}
fclose($dbcsv);
$searchf = searchForBarcode($post, $csvArray);
$result = $csvArray[$searchf];
$final = $result[+3];
if ($searchf !== NULL){
$stcsv = fopen('databases/stocktakemain.csv', 'r+');
$stArray = array();
while(! feof($stcsv))
{
$stArray[] = fgetcsv($stcsv);
}
fclose($stcsv);
$searchs = searchForBarcode($post, $stArray);
if ($searchs === NULL) {
$filew = 'databases/stocktakemain.csv';
$write = file_get_contents($filew);
$write .= print_r(implode(",",$result), true).",1'n";
file_put_contents($filew, $write);
}
else {
$filew = 'databases/stocktakemain.csv';
$resultexisting = $stArray[$searchs];
print_r($resultexisting);
echo "<br/>";
$getfilecont = file_get_contents($filew);
$getfilecont = trim($getfilecont);
$existing = explode(",", $getfilecont);
$existing[4] = trim($existing[4]);
++$existing[4];
print_r($existing);
echo "<br/>";
$writeto = print_r(implode(",",$existing), true);
print_r($writeto);
file_put_contents($filew, $writeto);
}
}
以下是我从阅读你的代码中得出的一些结论:
- 如果扫描的项目已经存在于stocktakkeep .csv文件中,则执行else块
-
$searchs
包含被扫描项目的行索引 -
$stArray
包含stocktakkeep .csv内容的二维数组—第一个索引是从0开始的行号,下一个索引是列号
基于此,我认为你需要重写你的else块,像这样:
$scQtyColumn = 4;
// what is the current quantity?
$scQty = intval($stArray[$searchs][$scQtyColumn]);
// update the quantity in the stocktakemain.csv contents array
$stArray[$searchs][$scQtyColumn] = $scQty + 1;
// write each line to file
$output = fopen('databases/stocktakemain.csv', 'w');
foreach($stArray, $line) {
fputcsv($output, $line);
}
你能试一下,看看它是否奏效吗?