您可以坚持使用相同的格式,但添加一个 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));
文档