我正在创建文本文件来存储我的变量来自一个网页。当用户单击添加按钮(如购物车)时,会将详细信息输入到服务器中的相应文本文件中。 我的代码如下:
$file = "../file/".$profile.".txt";
$qty=1;
$file_handle = fopen($file, "rb");
$profileID=mysql_query("SELECT * FROM `profile` WHERE `name`='$profile'",$con);
$profileID = mysql_fetch_row($profileID);
$profileID=$profileID[0];
$current = file_get_contents($file);
//$current.=file_put_contents($file, $profile."\n");
$result="SELECT p.*, pk.*,p.id as PID FROM `pricing` p
JOIN (SELECT `distributor`,MAX(`version`) AS ver FROM `pricing` GROUP BY `distributor`) mx ON mx.ver = p.version AND p.distributor = mx.distributor
JOIN `product_picker` pk ON pk.code = p.code AND pk.profile_name=$profileID AND p.id=$productID";
$result=mysql_query($result);
while($row = mysql_fetch_array($result))
{
$pricingID=$row['PID'];
$code=$row['code'];
$buy=$row['buy'];
$markup=$row['custom markup'];
$sell=$buy*$markup;
$buy="$".number_format((float)$sell,2,'.','');
$stock=explode('.',$row['stock']);
$stock=$stock[0];
}
if (file_exists($file))
{
$count=count(file($file));
while (!feof($file_handle) )
{
$line_of_text = fgets($file_handle);
$parts = explode('|', $line_of_text);
$pid=trim($parts[0]);
if($pid==$pricingID)
{
$qty=$qty+1;
}
}
fclose($file_handle);
}
$current.=$pricingID."|".$code.",".$buy.",".$stock."|".$qty."\n";
file_put_contents($file, $current);
根据代码,文本文件格式为:
793|EX-24-AFL,$2425.95,0|1
8078|EX-48-AFL,$3619.35,0|1
866|EX-PWR-320-AC,$303.24,20|1
793|EX-24-AFL,$2425.95,0|2
793|EX-24-AFL,$2425.95,0|3
第一列代表id(793,8078,866)。上面的代码每次都插入到文本文件中。但是如果文本文件的第一列id已经存在,我需要更改最后一个值(qty)。
因此文本文件的输出应为
793|EX-24-AFL,$2425.95,0|3
8078|EX-48-AFL,$3619.35,0|1
866|EX-PWR-320-AC,$303.24,20|1
有人请帮帮我吗?
答案 0 :(得分:2)
首先,我建议您不要为购物车编写自己的平面文件,而是在数据库中创建购物车表。
但是,如果您希望以这种方式继续,只需对现有代码进行少量更改即可完成您想要的任务。
if (file_exists($file))
{
$count=count(file($file));
$new_file_contents = ""; //contents to overwrite this file with
while (!feof($file_handle) )
{
$line_of_text = fgets($file_handle);
$parts = explode('|', $line_of_text);
$pid=trim($parts[0]);
if($pid==$pricingID)
{
$parts[2] = $qty + 1; //store incremented qty in array
$line_of_text = implode("|", $parts); //use implode to put array back together
}
$new_file_contents .= $line_of_text; //store this in new file contents
}
fclose($file_handle);
}
file_put_contents($file, $new_file_contents);
但是,我可能会用正则表达式来解决这个问题。我觉得这是解决这个问题的一种更简单的方法,并不涉及迭代文件的每一行。
if (file_exists($file))
{
$file_contents = file_get_contents($file);
$pattern = "/(${pid}\|[^\|]*\|)([0-9]+)/"; //establish regex pattern matching lines based on pid
preg_match($pattern, $file_contents, $matches); //match the line of this pid
$qty = $matches[2] + 1; //get the quantity currently in cart for this product and increment it
$replace = '${1}' . $qty; //build our replacement string using a callback and new quantity
$file_contents = preg_replace($pattern, $replace, $file_contents); //replace it in the file
file_put_contents($file, $file_contents); //overwrite old file with updated quantity
}