You could stick with the same format, but add an ID column, so you'd have this:
ProductID|Product name|Price|Quantity
ProductID|Product name|Price|Quantity
ProductID|Product name|Price|Quantity
Then use the ID field as the array key. You could use a similar approach with the product name, but you'd want to clean any spaces or special characters out.
$raw = file_get_contents($path);
$raw = explode("
", $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;
}
Now you'd have an array like this (for example):
array(
5=>array(
'Widget id #5',
'5.00',
'2'
),
11=>array(
'Widget id #11',
'6.00',
'1'
)
)
An even easier way would be to use JSON for the file format. That way, you don't have to monkey with parsing the data after you get it out of the file, and associative keys are easier to implement. Either way you do it, you'd follow the same steps:
- Get the data from the file and into a variable
- See if the product is already in the cart
- Increment the quantity by 1 (or any other number, really)
- Write the data back into a file
Using JSON, it would look something like this:
$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));
Documentation