Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm working on a basic shopping cart using a text file (just for educational purposes). It's formatted with one product on each line, like so:

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

How would I accomplish an addToCart() function that looks through the cart.txt file and either adds a product to a new line with a quantity of 1 if it's not already in the cart, or adds 1 to the quantity of that product if it's already in the cart?

share|improve this question

3 Answers

up vote 1 down vote accepted

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("\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;
  }

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
    • if not, add it
  • 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

share|improve this answer
thanks. your methodology of "see if the product is already in cart, if not add it, then increment quantity by 1 and write back" is extremely similar to what I was doing but more simple and effective – ejfrancis Mar 30 at 3:46

Maybe you can do some like this:

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);
    }
}

Please, take this as an idea.

share|improve this answer

You could look at using fgetcsv with a | delimiter.

share|improve this answer
I use explode() to split the lines and get the values, I'm asking how to specifically perform the functionality of adding 1 item to the cart.txt, by either adding a new line or modifying the existing entry – ejfrancis Mar 30 at 1:08
Why you want to use a .txt file? Do you want to learn how to manage file in php? I think you should use a database. – Overflow012 Mar 30 at 1:10
it's not my choice, it's a requirement for the project – ejfrancis Mar 30 at 1:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.