0

我正在使用文本文件(仅用于教育目的)制作基本的购物车。它的格式为每行一个产品,如下所示:

Product name|Price|Quantity 
Product name|Price|Quantity 
Product name|Price|Quantity 

我将如何完成一个 addToCart() 函数来查看 cart.txt 文件,如果它还没有在购物车中,则将产品添加到数量为 1 的新行,或者如果它是,则将 1 添加到该产品的数量已经在购物车里了?

4

3 回答 3

1

您可以坚持使用相同的格式,但添加一个 ID 列,这样您就有了:

ProductID|Product name|Price|Quantity 
ProductID|Product name|Price|Quantity 
ProductID|Product name|Price|Quantity 

然后使用 ID 字段作为数组键。您可以对产品名称使用类似的方法,但您需要清除所有空格或特殊字符。

  $raw = file_get_contents($path);
  $raw = explode("\n", $raw);
  $data = array();
  foreach ($raw as $d) {
    $d = explode('|', $d);
    // the left-most data will be our key
    $key = array_shift($d);
    $data[$key] = $d;
  }

现在你会有一个像这样的数组(例如):

array(
  5=>array(
    'Widget id #5',
    '5.00',
    '2'
  ),
  11=>array(
    'Widget id #11',
    '6.00',
    '1'
  )
)

一种更简单的方法是使用 JSON 作为文件格式。这样,您就不必在从文件中取出数据后对数据进行解析,并且关联键更容易实现。无论哪种方式,您都将遵循相同的步骤:

  • 从文件中获取数据并放入变量中
  • 查看产品是否已经在购物车中
    • 如果没有,添加它
  • 将数量增加 1(或任何其他数字,真的)
  • 将数据写回文件

使用 JSON,它看起来像这样:

$path = 'path/to/data.txt';
$data = json_decode(file_get_contents($path), true);

// if the product isn't in the cart, add it
if (array_key_exists($product_id, $data) === false) {

  // retrieve the product information for $product_id
  // populate $product_name and $product_price

  $data[$product_id] = array(
    'name'=>$product_name,
    'quantity'=>0,
    'price'=>$product_price
  );
}

// increment the quantity
$data[$product_id]['quantity']++;  // $data[$product_id][2]++ if you didn't use JSON

// write the data back into the file
file_put_contents($path, json_encode($data));

文档

于 2013-03-30T01:43:32.117 回答
0

您可以查看使用带有分隔符的fgetcsv 。|

于 2013-03-29T23:43:27.910 回答
0

也许你可以这样做:

function search_in_file($product_name, $price){
    $row = 1;
    $handle = fopen("cart.csv", "w"));
    if ( $handle !== FALSE) {
        while (($data = fgetcsv($handle, 0, "|")) !== FALSE) {
            if($data[0] == $product_name){
                $data[0] += 1;
                fclose($handle);
                return;
            }

        }
        fputcsv($handle, array($product_name, $price, 1);
        fclose($handle);
    }
}

请把这个当作一个想法。

于 2013-03-30T01:30:46.973 回答